【问题标题】:How do I use __str__ method to print list?如何使用 __str__ 方法打印列表?
【发布时间】:2019-05-08 07:04:49
【问题描述】:
class Deck:

    def __init__(self):
        self.cards=[]
        for suit in range(4):
            for rank in range(1,14):
                card=Card( suit, rank )
                self.cards.append(card)

    def __str__ (self):
        res=[]
        for card in self.cards:
            res.append(str(card))

        return '\n'.join(res)

    def pick_card(self):
        from random import shuffle
        shuffle(self.cards)
        return self.cards.pop()

    def add_card(self,card):
        if isinstance(card, Card): #check if card belongs to card Class!!
            self.cards.append(card)

    def move_cards(self, gen_hand, num):
        for i in range(num):
            gen_hand.add_card(self.pick_card())


class Hand(Deck):

    def __init__(self, label=''):
        self.cards = []
        self.label = label

    def __str__(self):
        return 'The {} is composed by {}'.format(self.label, self.cards)

mazzo_uno = Decks()
hand = Hand('New Hand')
mazzo_uno.move_cards(hand, 5)
print(hand)

我正在尝试学习面向对象的编程。当我尝试从子类 Hand() 打印对象 hand 时遇到了这个问题。我在 0x10bd9f978> 打印了类似 ma​​in.Card 对象,而不是 self.cards 列表中 5 张卡片的正确字符串名称:

The New Hand is composed by [<__main__.Card object at 0x10bd9f978>, 
<__main__.Card object at 0x10bd9fd30>, <__main__.Card object at 0x10bd9fe80>, 
<__main__.Card object at 0x10bcce0b8>, <__main__.Card object at 0x10bd9fac8>]

我也尝试这样做以将 self.cards 转换为字符串,但我得到了"TypeError: sequence item 0: expected str instance, Card found"

def __str__(self):
    hand_tostr = ', '.join(self.cards)
    return 'The {} is composed by {}'.format(self.label, hand_tostr)

我在本网站上阅读了应该使用 __repr__ 的其他答案,但我不明白如何在 Hand 类中添加它。

【问题讨论】:

  • 为你的班级添加__str__ Card,这样你就可以使用 str(card) 来获取字符串类型

标签: python string class oop methods


【解决方案1】:

__repr____str__ 用途不同,但工作方式相同。

您可以阅读this 以帮助您在两种方法之间进行选择。


您可以像这样更改 Hand 类的 __str__ 方法:

class Hand:

    def __str__(self):
        hand_tostr = ', '.join(map(str, self.cards)) # I use map to apply str() to each element of self.cards
        return 'The {} is composed by {}'.format(self.label, hand_tostr) 

如果你想改变 Card 类的 __repr__ 方法,你可以试试这样的方法(你没有提供 Card 类的代码)

class Card:
    #your code

    def __repr__(self):
        return <some string>

现在,如果您执行str(&lt;list of Card objects&gt;),它将在每个卡片实例上使用__repr__ 方法来显示您想要的内容。我不是这个解决方案的忠实拥护者,对于您的情况,我会使用第一个,因为您可能希望在其他情况下保留卡片对象的默认表示。


小心这段代码:

def add_card(self,card):
    if isinstance(card, Card): #check if card belongs to card Class!!
        self.cards.append(card)

如果 card 不是 Card 的实例,你不会提出任何东西。这意味着如果你用错误的参数使用这个方法,错误将被隐藏,你不会知道牌组没有改变。这是相当危险的。你可以这样做:

def add_card(self,card):
    assert(isinstance(card, Card)), "card parameter of add_card must be an instance of Card class"
    self.cards.append(card)

以更 Pythonic 的方式,您可以使用 typehint 通知您的类的用户 card 应该是 Card 的一个实例。然后相信python的duck-typing风格,或者使用mypy之类的工具来验证方法是否正确使用。

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2011-04-03
    • 2022-11-23
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多