__str__ dunder 方法仍然返回 <__main__. object > 而不是字符串

问题描述 投票:0回答:1

我正在尝试定义一个类并让它返回格式正确的字符串。但是,它返回与我在没有

str
dunder 方法的情况下打印类时相同的 <__main__.Card object at 0x7fb4439e4d00> 结果。我认为这与我首先没有将参数传递到类中有关。任何解释将不胜感激,谢谢。

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__())
python oop
1个回答
0
投票

__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(str(x))
© www.soinside.com 2019 - 2024. All rights reserved.