__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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM