__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