简体   繁体   English

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

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

I am doing a mini project in Coursera. 我正在Coursera做一个迷你项目。 ( Card is another class which has been declared elsewhere.) 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

I understand that the list self.deck contains a list of Card objects, Can anyone tell me how to print the value of self.deck (which this object is referring to) in my __str__ method? 我知道列表self.deck包含Card对象的列表,谁能告诉我如何在__str__方法中打印self.deck的值(此对象所指)?

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

return str(self.deck)

You can also do like this: 您也可以这样:

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

After, each of the Card instances of the deck must have their own str method overridden so that it formats properly too. 之后,卡片组的每个Card实例都必须具有自己的str方法,以使其也能正确格式化。

Python's Docs should tell you how to use __str__ . Python的文档应该告诉您如何使用__str__

Basically when you do: 基本上,当您这样做时:

print something

Python calls the __str__ method of something and writes that to the output. Python调用something__str__方法并将其写入输出。

Based on my guess, you would probably want to print fact that this object is a deck. 根据我的猜测,您可能希望打印出该对象是套牌的事实。 So something like this might be what you want: 因此,您可能想要这样的东西:

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

Since you are learning Python, I have a bunch of suggestions: 由于您正在学习Python,因此我有很多建议:

  1. As @abarnert said, when you do class ABC: in Python 2, it is an old-style class. 就像@abarnert所说的那样,当您对class ABC:class ABC:在Python 2中,它是一个老式的类。 (More here ) (更多在这里
  2. Although not necessary, you should have a empty lines before every function. 尽管不是必需的,但在每个函数之前都应该有一个空行。
  3. Avoid using single-character variable names. 避免使用单字符变量名。 (like i and j ) (如ij

So, your code (should) look like: 因此,您的代码(应该)如下所示:

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()"

And lastly, you might want to read this , which turns out to be the same page as the one I linked before, twice. 最后,您可能需要阅读this ,结果与我之前链接的页面是同一页面两次。

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

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