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

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

Not understanding my __str__ doesn't seem to be working

问题

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

我是Python中的类新手正在制作一个基于文本的二十一点游戏以更熟悉它们我面临的最大问题是让`__str__`方法按预期工作有时候它工作得很好在下面显示的`Deck`类中),但其他时候却不工作返回对象类型在下面显示的`PlayerHand`类中)。我尝试了不同的格式样式还将要打印的内容转换为字符串但都没有成功

import random

card_suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds']

card_names = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
'Nine', 'Ten', 'Jack', 'Queen', 'King']

---

class Deck:

    def __init__(self):
        pass

    def shuffled_deck(self):
        # 当类实例被调用时,创建新的牌组并洗牌
        initial_deck = []
        for suit in card_suits:
            for name in card_names:
                initial_deck.append(Card(name, suit))
                random.shuffle(initial_deck)
        self.initial_deck = initial_deck

    def remove_card(self):
        removed = []
        removed = self.initial_deck.pop()
        self.removed = removed
        return self.removed

    def __str__(self):
        return str(self.removed)

---

class PlayerHand(Deck):

    def __init__(self):
        pass

    # 发牌
    def p1(self):
        p1_hand = []
        for card in [0, 1]:
            p1_hand.append(Deck.remove_card(self))
            self.p1_hand = p1_hand
        return self.p1_hand

    def __str__(self):
        return str(self.p1_hand[0])

---

Current_Hand = PlayerHand()
Current_Hand.shuffled_deck()
Current_Hand.p1()
print(PlayerHand)

输出:

<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.

import random
card_suits = [&#39;Hearts&#39;,&#39;Spades&#39;,&#39;Clubs&#39;,&#39;Diamonds&#39;]
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;,
&#39;Nine&#39;,&#39;Ten&#39;,&#39;Jack&#39;,&#39;Queen&#39;,&#39;King&#39;]

class Deck:
def __init__(self):
pass
def shuffled_deck(self):
#Make new Deck and shuffle when class instance is called
initial_deck = []
for suit in card_suits:
for name in card_names:
initial_deck.append(Card(name,suit))
random.shuffle(initial_deck)
self.initial_deck = initial_deck
def remove_card(self):
removed = []
removed = self.initial_deck.pop()
self.removed = removed
return self.removed
def __str__(self):
return str(self.removed)

class PlayerHand(Deck):
def __init__(self):
pass
#Deal cards
def p1(self):
p1_hand = []
for card in [0,1]:
p1_hand.append(Deck.remove_card(self))
self.p1_hand = p1_hand
return self.p1_hand
def __str__(self):
return str(self.p1_hand[0])

Current_Hand = PlayerHand()
Current_Hand.shuffled_deck()
Current_Hand.p1()
print(PlayerHand)

Outputs:

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

答案1

得分: 0

以下是翻译好的部分:

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

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

例如:

from random import shuffle
from typing import Self

class Card:
    def __init__(self, suit, rank, value):
        self.suit = suit
        self.rank = rank
        self.value = value

    def __str__(self) -> str:
        return f'{self.rank} of {self.suit}'

class Deck:
    SUITS = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
    RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
             'Nine', 'Ten', 'Jack', 'Queen', 'King']
    VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

    def __init__(self):
        self.cards = [Card(suit, rank, value) for (rank, value) in zip(Deck.RANKS, Deck.VALUES) for suit in Deck.SUITS]
        shuffle(self.cards)

    def __str__(self) -> str:
        return '\n'.join(str(card) for card in self.cards)

    def draw(self) -> Card:
        assert len(self.cards) > 0
        return self.cards.pop()

class Player:
    def __init__(self, deck):
        self.deck = deck
        self.hand = []

    def deal(self, n: int = 1) -> Self:
        self.hand += [self.deck.draw() for _ in range(n)]
        return self

    def __str__(self) -> str:
        if self.hand:
            return ', '.join(str(card) for card in self.hand)
        return 'Empty hand'

    def value(self) -> tuple[int, ...]:
        _min, _max = 0, 0
        for card in self.hand:
            _min += card.value
            _max += card.value
            if card.value == 1:  # Ace
                _max += 10
        return (_min,) if _min == _max else (_min, _max)

deck = Deck()

player_1 = Player(deck).deal(2)
player_2 = Player(deck).deal(2)

print(player_1, player_1.value())
print(player_2, player_2.value())

for _ in range(2):
    player_1.deal()
    print(player_1, player_1.value())
    player_2.deal()
    print(player_2, player_2.value())

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

Eight of Hearts, Five of Diamonds (13,)
Six of Hearts, Three of Diamonds (9,)
Eight of Hearts, Five of Diamonds, Seven of Diamonds (20,)
Six of Hearts, Three of Diamonds, Ten of Hearts (19,)
Eight of Hearts, Five of Diamonds, Seven of Diamonds, Three of Hearts (23,)
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.

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

For example:

from random import shuffle
from typing import Self
class Card:
def __init__(self, suit, rank, value):
self.suit = suit
self.rank = rank
self.value = value
def __str__(self) -&gt; str:
return f&#39;{self.rank} of {self.suit}&#39;
class Deck:
SUITS = [&#39;Hearts&#39;, &#39;Spades&#39;, &#39;Clubs&#39;, &#39;Diamonds&#39;]
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;,
&#39;Nine&#39;, &#39;Ten&#39;, &#39;Jack&#39;, &#39;Queen&#39;, &#39;King&#39;]
VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def __init__(self):
self.cards = [Card(suit, rank, value) for (rank, value) in zip(Deck.RANKS, Deck.VALUES) for suit in Deck.SUITS]
shuffle(self.cards)
def __str__(self) -&gt; str:
return &#39;\n&#39;.join(str(card) for card in self.cards)
def draw(self) -&gt; Card:
assert len(self.cards) &gt; 0
return self.cards.pop()
class Player:
def __init__(self, deck):
self.deck = deck
self.hand = []
def deal(self, n: int=1) -&gt; Self:
self.hand += [self.deck.draw() for _ in range(n)]
return self
def __str__(self) -&gt; str:
if self.hand:
return &#39;, &#39;.join(str(card) for card in self.hand)
return &#39;Empty hand&#39;
def value(self) -&gt; tuple[int, ...]:
_min, _max = 0, 0
for card in self.hand:
_min += card.value
_max += card.value
if card.value == 1: # Ace
_max += 10
return (_min,) if _min == _max else (_min, _max)
deck = Deck()
player_1 = Player(deck).deal(2)
player_2 = Player(deck).deal(2)
print(player_1, player_1.value())
print(player_2, player_2.value())
for _ in range(2):
player_1.deal()
print(player_1, player_1.value())
player_2.deal()
print(player_2, player_2.value())

Output (example because it's random):

Eight of Hearts, Five of Diamonds (13,)
Six of Hearts, Three of Diamonds (9,)
Eight of Hearts, Five of Diamonds, Seven of Diamonds (20,)
Six of Hearts, Three of Diamonds, Ten of Hearts (19,)
Eight of Hearts, Five of Diamonds, Seven of Diamonds, Three of Hearts (23,)
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.

# your code ...

Current_Hand = PlayerHand()
Current_Hand.shuffled_deck()
Current_Hand.p1()
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:

确定