不理解我的 __str__ 似乎不起作用

huangapple go评论109阅读模式
英文:

Not understanding my __str__ doesn't seem to be working

问题

以下是翻译好的代码部分:

  1. 我是Python中的类新手正在制作一个基于文本的二十一点游戏以更熟悉它们我面临的最大问题是让`__str__`方法按预期工作有时候它工作得很好在下面显示的`Deck`类中),但其他时候却不工作返回对象类型在下面显示的`PlayerHand`类中)。我尝试了不同的格式样式还将要打印的内容转换为字符串但都没有成功
  2. import random
  3. card_suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
  4. card_names = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
  5. 'Nine', 'Ten', 'Jack', 'Queen', 'King']
  6. ---
  7. class Deck:
  8. def __init__(self):
  9. pass
  10. def shuffled_deck(self):
  11. # 当类实例被调用时,创建新的牌组并洗牌
  12. initial_deck = []
  13. for suit in card_suits:
  14. for name in card_names:
  15. initial_deck.append(Card(name, suit))
  16. random.shuffle(initial_deck)
  17. self.initial_deck = initial_deck
  18. def remove_card(self):
  19. removed = []
  20. removed = self.initial_deck.pop()
  21. self.removed = removed
  22. return self.removed
  23. def __str__(self):
  24. return str(self.removed)
  25. ---
  26. class PlayerHand(Deck):
  27. def __init__(self):
  28. pass
  29. # 发牌
  30. def p1(self):
  31. p1_hand = []
  32. for card in [0, 1]:
  33. p1_hand.append(Deck.remove_card(self))
  34. self.p1_hand = p1_hand
  35. return self.p1_hand
  36. def __str__(self):
  37. return str(self.p1_hand[0])
  38. ---
  39. Current_Hand = PlayerHand()
  40. Current_Hand.shuffled_deck()
  41. Current_Hand.p1()
  42. print(PlayerHand)
  43. 输出:
  44. <class '__main__.PlayerHand'>

请注意,代码中存在一些问题,需要修复。如果您需要有关代码问题的更多帮助,请告诉我。

英文:

I am new to classes in Python and I am making a text based version of Blackjack to get more familiar with them. The biggest issue I am facing is getting the __str__ method to work as expected. Some of the time it works fine (In the Deck class shown below), but other times it does not and returns the object type (The PlayerHand class shown below). I have tried different formatting styles and converted what I want to print out to string as well with no avail.

  1. import random
  2. card_suits = [&#39;Hearts&#39;,&#39;Spades&#39;,&#39;Clubs&#39;,&#39;Diamonds&#39;]
  3. card_names = [&#39;Ace&#39;,&#39;Two&#39;,&#39;Three&#39;,&#39;Four&#39;,&#39;Five&#39;,&#39;Six&#39;,&#39;Seven&#39;,&#39;Eight&#39;,
  4. &#39;Nine&#39;,&#39;Ten&#39;,&#39;Jack&#39;,&#39;Queen&#39;,&#39;King&#39;]

  1. class Deck:
  2. def __init__(self):
  3. pass
  4. def shuffled_deck(self):
  5. #Make new Deck and shuffle when class instance is called
  6. initial_deck = []
  7. for suit in card_suits:
  8. for name in card_names:
  9. initial_deck.append(Card(name,suit))
  10. random.shuffle(initial_deck)
  11. self.initial_deck = initial_deck
  12. def remove_card(self):
  13. removed = []
  14. removed = self.initial_deck.pop()
  15. self.removed = removed
  16. return self.removed
  17. def __str__(self):
  18. return str(self.removed)

  1. class PlayerHand(Deck):
  2. def __init__(self):
  3. pass
  4. #Deal cards
  5. def p1(self):
  6. p1_hand = []
  7. for card in [0,1]:
  8. p1_hand.append(Deck.remove_card(self))
  9. self.p1_hand = p1_hand
  10. return self.p1_hand
  11. def __str__(self):
  12. return str(self.p1_hand[0])

  1. Current_Hand = PlayerHand()
  2. Current_Hand.shuffled_deck()
  3. Current_Hand.p1()
  4. print(PlayerHand)

Outputs:

  1. &lt;class &#39;__main__.PlayerHand&#39;&gt;

答案1

得分: 0

以下是翻译好的部分:

有很多问题与这种编写方式有关。

首先,没有必要使用继承(子类化)。
在构建时应洗牌牌组。
Player 类的每个实例应该使用相同的牌组。
卡片有值 - 你应该考虑到这一点。
如果将 Ace 视为 1 或 11,则一手可能有多个值。

例如:

  1. from random import shuffle
  2. from typing import Self
  3. class Card:
  4. def __init__(self, suit, rank, value):
  5. self.suit = suit
  6. self.rank = rank
  7. self.value = value
  8. def __str__(self) -> str:
  9. return f'{self.rank} of {self.suit}'
  10. class Deck:
  11. SUITS = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
  12. RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
  13. 'Nine', 'Ten', 'Jack', 'Queen', 'King']
  14. VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  15. def __init__(self):
  16. self.cards = [Card(suit, rank, value) for (rank, value) in zip(Deck.RANKS, Deck.VALUES) for suit in Deck.SUITS]
  17. shuffle(self.cards)
  18. def __str__(self) -> str:
  19. return '\n'.join(str(card) for card in self.cards)
  20. def draw(self) -> Card:
  21. assert len(self.cards) > 0
  22. return self.cards.pop()
  23. class Player:
  24. def __init__(self, deck):
  25. self.deck = deck
  26. self.hand = []
  27. def deal(self, n: int = 1) -> Self:
  28. self.hand += [self.deck.draw() for _ in range(n)]
  29. return self
  30. def __str__(self) -> str:
  31. if self.hand:
  32. return ', '.join(str(card) for card in self.hand)
  33. return 'Empty hand'
  34. def value(self) -> tuple[int, ...]:
  35. _min, _max = 0, 0
  36. for card in self.hand:
  37. _min += card.value
  38. _max += card.value
  39. if card.value == 1: # Ace
  40. _max += 10
  41. return (_min,) if _min == _max else (_min, _max)
  42. deck = Deck()
  43. player_1 = Player(deck).deal(2)
  44. player_2 = Player(deck).deal(2)
  45. print(player_1, player_1.value())
  46. print(player_2, player_2.value())
  47. for _ in range(2):
  48. player_1.deal()
  49. print(player_1, player_1.value())
  50. player_2.deal()
  51. print(player_2, player_2.value())

输出(示例,因为它是随机的):

  1. Eight of Hearts, Five of Diamonds (13,)
  2. Six of Hearts, Three of Diamonds (9,)
  3. Eight of Hearts, Five of Diamonds, Seven of Diamonds (20,)
  4. Six of Hearts, Three of Diamonds, Ten of Hearts (19,)
  5. Eight of Hearts, Five of Diamonds, Seven of Diamonds, Three of Hearts (23,)
  6. Six of Hearts, Three of Diamonds, Ten of Hearts, Ace of Clubs (20, 30)
英文:

There are numerous issues with the way this has been written.

  1. Firstly, there is no need for inheritance (subclassing).
  2. The deck should be shuffled upon construction.
  3. Each instance of a Player class should be using the same deck.
  4. Cards have values - you should account for that.
  5. A hand may have multiple values if Ace is considered to have a value of 1 or 11.

For example:

  1. from random import shuffle
  2. from typing import Self
  3. class Card:
  4. def __init__(self, suit, rank, value):
  5. self.suit = suit
  6. self.rank = rank
  7. self.value = value
  8. def __str__(self) -&gt; str:
  9. return f&#39;{self.rank} of {self.suit}&#39;
  10. class Deck:
  11. SUITS = [&#39;Hearts&#39;, &#39;Spades&#39;, &#39;Clubs&#39;, &#39;Diamonds&#39;]
  12. RANKS = [&#39;Ace&#39;, &#39;Two&#39;, &#39;Three&#39;, &#39;Four&#39;, &#39;Five&#39;, &#39;Six&#39;, &#39;Seven&#39;, &#39;Eight&#39;,
  13. &#39;Nine&#39;, &#39;Ten&#39;, &#39;Jack&#39;, &#39;Queen&#39;, &#39;King&#39;]
  14. VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  15. def __init__(self):
  16. self.cards = [Card(suit, rank, value) for (rank, value) in zip(Deck.RANKS, Deck.VALUES) for suit in Deck.SUITS]
  17. shuffle(self.cards)
  18. def __str__(self) -&gt; str:
  19. return &#39;\n&#39;.join(str(card) for card in self.cards)
  20. def draw(self) -&gt; Card:
  21. assert len(self.cards) &gt; 0
  22. return self.cards.pop()
  23. class Player:
  24. def __init__(self, deck):
  25. self.deck = deck
  26. self.hand = []
  27. def deal(self, n: int=1) -&gt; Self:
  28. self.hand += [self.deck.draw() for _ in range(n)]
  29. return self
  30. def __str__(self) -&gt; str:
  31. if self.hand:
  32. return &#39;, &#39;.join(str(card) for card in self.hand)
  33. return &#39;Empty hand&#39;
  34. def value(self) -&gt; tuple[int, ...]:
  35. _min, _max = 0, 0
  36. for card in self.hand:
  37. _min += card.value
  38. _max += card.value
  39. if card.value == 1: # Ace
  40. _max += 10
  41. return (_min,) if _min == _max else (_min, _max)
  42. deck = Deck()
  43. player_1 = Player(deck).deal(2)
  44. player_2 = Player(deck).deal(2)
  45. print(player_1, player_1.value())
  46. print(player_2, player_2.value())
  47. for _ in range(2):
  48. player_1.deal()
  49. print(player_1, player_1.value())
  50. player_2.deal()
  51. print(player_2, player_2.value())

Output (example because it's random):

  1. Eight of Hearts, Five of Diamonds (13,)
  2. Six of Hearts, Three of Diamonds (9,)
  3. Eight of Hearts, Five of Diamonds, Seven of Diamonds (20,)
  4. Six of Hearts, Three of Diamonds, Ten of Hearts (19,)
  5. Eight of Hearts, Five of Diamonds, Seven of Diamonds, Three of Hearts (23,)
  6. Six of Hearts, Three of Diamonds, Ten of Hearts, Ace of Clubs (20, 30)

答案2

得分: 0

你正在尝试显示类本身,而不是其实例,你应该直接打印Current_Hand,因为这个变量是一个实例。

英文:

You are trying to display the class itself, not an instance of it, you should directly print Current_Hand, because this variable is an instance.

  1. # your code ...
  2. Current_Hand = PlayerHand()
  3. Current_Hand.shuffled_deck()
  4. Current_Hand.p1()
  5. print(Current_Hand)

huangapple
  • 本文由 发表于 2023年8月10日 14:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定