__str__ OOP Python 类的 dunder 方法仍然返回 <__main__. 对象>而不是字符串



我正在尝试定义一个类,并让它返回一个格式正确的字符串。但是,它返回的<__main__.Card object at 0x7fb4439e4d00>结果与我打印没有strdunder方法的类时相同。我认为这与我一开始没有向类传递任何参数有关。任何解释都将不胜感激,谢谢。

class Card:
    def __init__(self):
        self.shape = "diamond"
        self.fill = random.choice(fill)
        self.number = random.choice(number)
        self.color = random.choice(color)
        def __str__(self):
            return f"{self.number}-{self.color}-{self.fill}-{self.shape}.png"
x = Card()
print(x)
print(x.__str__())

__str__方法的缩进错误。您的代码应该是:

class Card:
    def __init__(self):
        self.shape = "diamond"
        self.fill = random.choice(fill)
        self.number = random.choice(number)
        self.color = random.choice(color)
    def __str__(self):
        return f"{self.number}-{self.color}-{self.fill}-{self.shape}.png"

x = Card()
print(x)
print(x.__str__())

最新更新