如何在面向对象的编程python中实现这一点 什么打印 str 方法返回的内容?
class Bike():
def __str__(self):
return Components.__str__(self)+", "+ self.getFrameType()
def printComponents(self):
print(Bike.self())
答案 0 :(得分:1)
如果要将其转换为字符串,则会调用__str__
方法。
class Bike():
def __init__(self):
self.hello = "hello"
def __str__(self):
return self.hello + " goodbye"
>>> print(str(Bike()))
"hello goodbye"
如果您打算直接打印对象,即使用print(Bike())
,则您希望使用__repr__
。有关详细信息,请参阅here。