__str__()方法

只要定义了__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>

 

posted @ 2019-07-04 11:56  世纪强风  阅读(1667)  评论(0编辑  收藏  举报