类中的特殊方法
類中的特殊方法
?1,類名()自動執(zhí)行__init__ :
作用:初始化實例的變量2,對象()自動執(zhí)行__call__ :
# __call__ 實例執(zhí)行的時候會執(zhí)行此方法 class Foo:def __call__(self, *args, **kwargs):print(args,kwargs)return 123 #__call__方法還有返回值 obj=Foo() obj(22,33,k1=222)
ret=obj(22,33) #在這里可以接收下返回值
3,對象 [“xxx” ]? 自動執(zhí)行__getitem__ :
class Foo:def __getitem__(self, item):print(111)return item obj=Foo() ret=obj['yu'] #可以通過這種方法把自己定義的類的實例做成類似列表的功能 print(ret)
4,對象 [“xxx” ] ==123 自動執(zhí)行__setitem__ :
class Foo:def __setitem__(self, item):print(111)return item obj=Foo() obj["k1"]=123 #這個是沒有返回值的,在語法上就不允許,如果接收ret= obj["k1"]=123,就表示兩個都等于123?這顯然不是5, del? ? 對象 [“xxx” ]? 自動執(zhí)行__delitem__ :
class Foo:def __setitem__(self, key):print(111)#這個方法沒有返回值 obj=Foo() del obj["k1"]6,對象+對象? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#相應(yīng)的語法就對應(yīng)了面向?qū)ο笾械奶厥獾姆椒?#xff0c;面向?qū)ο笾械奶厥夥椒ê芏?/p> class Foo():def __init__(self,a1,a2):self.a1=a1self.a2=a2def __add__(self, other):return self.a1 + other.a2obj1=Foo(1,2) obj2=Foo(88,99) ret=obj1+obj2 print(ret)
7,with 對象
class Foo():def __init__(self,a1,a2):self.a1=a1self.a2=a2def __enter__(self):print(11111)def __exit__(self, exc_type, exc_val, exc_tb):print(2222)obj1=Foo(1,2) obj2=Foo(88,99)with obj1: #pass #要點,只要with遇到一個對象,就會立馬執(zhí)行類中的__enter__方法和__exit__方法,所以即便這里用占位符pass,類中的兩個方法也會執(zhí)行的print("hello word") #當(dāng)然在進入和退出之間也可以寫一些自己的代碼塊
?
class Foo():def __init__(self,a1,a2):self.a1=a1self.a2=a2def __enter__(self):print(11111)return 666def __exit__(self, exc_type, exc_val, exc_tb):print(2222)obj1=Foo(1,2) obj2=Foo(88,99)with obj1 as f: #在這里可以寫一個as f 來接收一下__enter__方法的返回值print(f) print("hello word") #8 正真的構(gòu)造方法
class Foo():def __init__(self,a1,a2):print(1)self.a1=a1self.a2=a2def __new__(cls, *args, **kwargs):print(2)pass Foo(1,2) #__new__方法執(zhí)行了,但是__init__方法沒有執(zhí)行,是因為__new__方法必須返回會一個值,對象才能創(chuàng)建?
要想l兩個方法都執(zhí)行必須給__new__方法設(shè)置返回值
class Foo():def __init__(self,a1,a2):print(1)self.a1=a1self.a2=a2def __new__(cls, *args, **kwargs):return object.__new__(cls) #所有的對象都是object創(chuàng)建的,因為所有的對象都繼承自object,#所以創(chuàng)建對象的過程是這樣的,object 創(chuàng)建一個空的當(dāng)前類的對象,然后,__init__#做初始化,再給對象里面填值 Foo(1,2)#在其他語言中的構(gòu)造方法是合在一起的,python中把他分開了,兩個功能不一樣 #所以一般這樣說__init__是初始化方法 # __new__是構(gòu)造方法
?
轉(zhuǎn)載于:https://www.cnblogs.com/zhuhaofeng/p/9563000.html
總結(jié)
- 上一篇: 【ASP.NET】 【防止连续多次点击提
- 下一篇: 医疗AI技术火热,但其商业模式的落脚点究