__str__方法:
使用:如:
class Car:
def __init__(self,
newWheelNum, newColor):
self.wheelNum =
newWheelNum
self.color =
newColor
def __str__(self):
msg = "嘿。。。我的颜色是" + self.color + "我有" + int(self.wheelNum) + "个轮胎..."
return msg
def move(self):
print('车在跑,目标:夏威夷')
BMW = Car(4, "白色")
print(BMW)
总结:
在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法
当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
也即打印对象时会触发类的__str__(self)方法。
如果没有定义这个内置的方法,打印对象时,会输出对象的内存地址。
类中定义了这个方法,当打印对象时,会执行__str__这个方法。这个方法必须有字符串的返回值。
小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)
GMT+8, 2024-5-4 05:06
Powered by Discuz! X3.4
© 2001-2023 Discuz! Team.