我正在尝试定义一个类并让它返回格式正确的字符串。但是,它返回与我在没有
strdunder 方法的情况下打印类时相同的
<__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__())
__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))