2

我正在实例化一个类,只是想使用 print 转储对象。当我这样做时,我似乎得到了某种对象 ID。我不能只发出一个“打印 ObjectName”,结果就是对象的属性吗?这是我正在做的一个例子:

class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model

    def getAll():
        return (self.color, self.make, self.model)


mycar = Car("white","Honda","Civic")
print mycar

当我运行它时,我得到以下结果:

<__main__.Car instance at 0x2b650357be60>

我也希望看到颜色、品牌、型号的值。我知道我是否通过以下方式单独打印它们:

print mycar.color,mycar.make,mycar.model

它输出:

white Honda Civic

正如我所期望的那样。为什么“print mycar”输出的是实例 id 而不是属性值?

4

2 回答 2

3

在你的类上定义一个.__str__()方法。打印自定义类实例时会调用它:

class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model

    def __str__(self):
        return ' '.join((self.color, self.make, self.model))

演示:

>>> mycar = Car("white","Honda","Civic")
>>> print mycar
white Honda Civic

In addition, you could implement a .__repr__() method too, to provide a debugger-friendly representation of your instances.

于 2013-03-29T16:27:47.873 回答
2

You need to implement __str__ and __repr__ to get "friendly" values for your class objects.

Look here for more details on this.

__repr__ is the official string represntation of an object and is called by repr() and __str__ is the informal string representation and is called by str()

于 2013-03-29T16:28:56.250 回答