Python中的魔法方法總結(持續更新)
python中的魔法方法總結
__str__
當使用print輸出對象的時候,只要自己定義了__str__(self)
方法,那麼就會打印從這個方法中return的數據。舉個例子:
class Cat:
"""定義了一個Cat類"""
#初始化對象
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年齡是:%d"%(self.name, self.age)
#方法
def eat(self):
print("貓在吃魚....")
def drink(self):
print("貓正在喝kele.....")
def introduce(self):
print("%s的年齡是:%d"%(self.name, self.age))
#創建一個對象
tom = Cat("湯姆", 40)
lanmao = Cat("藍貓", 10)
print(tom)
print(lanmao)
---------------------
作者:一如故往
來源:CSDN
原文:https://blog.csdn.net/qq_37616069/article/details/79387010
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
運行程序的結果爲:
湯姆的年齡是:40
藍貓的年齡是:10