实例应该能够使用方法打印其组件

时间:2015-11-19 06:36:51

标签: python python-3.x

如何在面向对象的编程python中实现这一点 什么打印 str 方法返回的内容?

class Bike():

    def __str__(self):
        return Components.__str__(self)+", "+ self.getFrameType()

    def printComponents(self):
        print(Bike.self())

1 个答案:

答案 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