對於魔法函式__repr__來說,他是可以把乙個物件用字串表達出來,以便於更好的區分,對於__str__來說,它也是返回字串,只是對於終端使用者更友好一些。
class
person
:def
__init__
(self,name,hobbys)
: self.name = name
self.hobbys = hobbys
def__repr__
(self)
:return
"this is %s"
%self.name
bob = person(
"bob",[
"ball"
,"game"])
print
(bob)
列印的結果
c:\python35\python.exe e:/pytest/pytest8.5.py
this is bob
process finished with exit code 0
未完待續 python高階程式設計 2 魔法函式
在觸發某些條件的情況下回自動呼叫的函式,以雙下劃線開頭和結尾,例如 iter getitem class company object def init self,employee list self.employee list employee list def getitem self,item...
python魔法函式
python中魔法函式簡單上來說就是在構建某個類的時候,給類定義一些初始的方法,來實現類物件的某些屬性或者方法而準備。其形式如下,下雙劃線開頭雙劃線結尾 初始化乙個學生class class student def init self,students list self.students list...
python 魔法函式
python中以 開頭,以 結尾的函式就是魔法函式,類中的魔法函式是為了增強類的特性。魔法函式不能自定義。同時魔法函式定義之後不需要呼叫,直譯器會自動進行呼叫。class company object def init self,employee list self.employee employe...