[英]how to activate __str__ dunder method using instance and fix error:"__str__ returned non-string (type NoneType)"
[英]__str__ dunder method for OOP Python class still returns <__main__. object > instead of string
我正在尝试定义一个 class 并让它返回一个格式正确的字符串。 但是,它返回相同的<__main__.Card object at 0x7fb4439e4d00>
结果,就像我在没有str dunder 方法的情况下打印 class 时一样。 我认为这与我首先没有将参数传递给 class 的事实有关。 任何解释将不胜感激,谢谢。
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__())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.