只要定義了__str__(self)方法,那么就會打印從這個方法中return的數據
class Car:
def __init__(self, newWheelNum, newColor):
self.wheelNum = newWheelNum
self.color = newColor
def __str__(self):
msg = "My color:" + self.color + ", my wheel num:" + str(self.wheelNum)
return msg
def move(self):
print "Car is running ..."
BMW = Car(4, "White")
print BMW
輸出:My color:White, my wheel num:4
如果將__str__()函數注釋掉
print BMW的輸出是:
<__main__.Car instance at 0x0000000003780C08>