python - 类对象不打印

标签 python class

我的类对象不会在 Python 中打印。这是我的代码:

import random

suits = ("Hearts", "Diamonds", "Spades", "Clubs")
ranks = ("Two","Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace")
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
         'Queen':10, 'King':10, 'Ace':11}

playing = True

class Card:

    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return self.rank + " of " + self.suit

class Deck:

    def __init__(self):
        self.deck = []  # start with an empty list
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))

    def __str__(self):
        return self.deck

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        pass

test_deck = Deck()
#len(test_deck.deck)
print(test_deck)

此代码的最后一行 print(test_deck) 给出了以下错误,我不知道为什么,因为我正在遵循使用 __str__ 进行打印的类似示例一个类对象:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
      1 test_deck = Deck()
      2 len(test_deck.deck)
----> 3 print(test_deck)

TypeError: __str__ returned non-string (type list)

我不知道为什么我无法打印列表?即使我使用了return

最佳答案

__str__方法必须返回字符串格式

你可以这样重写

def __str__(self):
    return ", ".join([str(card) for card in self.deck])

所以它会打印这样的内容

Two of Hearts, Five of Diamonds

或者如果你想显式地表明它是一个列表结构,只需返回 str(self.deck)

所以它会打印这样的内容

"[<__main__.Card object at 0x7f8ad5a1e190>, <__main__.Card object at 0x7f8ad5a1e190>]"

关于python - 类对象不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411969/

相关文章:

python - 没有 * 的 Tkinter 导入?

css - 如何从 rel 属性 CSS 将样式更改为类

r - 在R中,处理错误:ggplot2不知道如何处理数值类的数据

python - 如何在树莓派上更新到最新的 python 3.5.1 版本?

python - 如何迭代列表并创建子列表

c++ - 赋值运算符的返回类型

c++ - 将 pimpl 样式类定义编译并链接到库中 (C++)

Java : How to create an object in a method and use it throughout the class?

python - 如何从数据框中删除/替换任何字符串?

python - Flask 的 Cassandra 连接池