繁体   English   中英

使用__str__打印对象的数组元素

[英]Using __str__ for printing array elements of an object

我正在Coursera做一个迷你项目。 Card是另一种已在其他地方声明的类。)

class Deck:    
    def __init__(self):
        self.deck = []
        for i in SUITS:
            for j in RANKS:
                self.deck.append(Card(str(i), str(j)))
    def deal_card(self):
        self.temp = random.randrange(0,52)        
        return(self.deck[self.temp])

    def __str__(self):
        #TODO

main()
test_deck = Deck()
c1 = test_deck.deal_card()
print test_deck

我知道列表self.deck包含Card对象的列表,谁能告诉我如何在__str__方法中打印self.deck的值(此对象所指)?

只需将其转换为字符串即可。

return str(self.deck)

您也可以这样:

def __str__(self):
  return ','.join(str(x) for x in self.deck)

之后,卡片组的每个Card实例都必须具有自己的str方法,以使其也能正确格式化。

Python的文档应该告诉您如何使用__str__

基本上,当您这样做时:

print something

Python调用something__str__方法并将其写入输出。

根据我的猜测,您可能希望打印出该对象是套牌的事实。 因此,您可能想要这样的东西:

class Deck:
    # ...
    def __str__(self):
        return "Deck()"

由于您正在学习Python,因此我有很多建议:

  1. 就像@abarnert所说的那样,当您对class ABC:class ABC:在Python 2中,它是一个老式的类。 (更多在这里
  2. 尽管不是必需的,但在每个函数之前都应该有一个空行。
  3. 避免使用单字符变量名。 (如ij

因此,您的代码(应该)如下所示:

class Deck(object):

    def __init__(self):  # Blank line above...
        self.deck = []
        # Change variable names...
        for suit in SUITS:
            for rank in RANKS:
                self.deck.append(Card(str(suit), str(rank)))

    def deal_card(self):  # Blank line above...
        self.temp = random.randrange(0,52)
        return(self.deck[self.temp])

    def __str__(self):
        return "Deck()"

最后,您可能需要阅读this ,结果与我之前链接的页面是同一页面两次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM