進一步認識__new__和__call__,認識__new___call_

來源:互聯網
上載者:User

進一步認識__new__和__call__,認識__new___call_

1.關於__init__

class F00(object):
def __init__(self,name):
self.name = name
print("Foo--init--")
def __new__(cls, *args, **kwargs):
print("Foo--new--")
return object.__new__(cls)#cls表示將Foo類傳進__new__方法中,表示繼父類的__new__方法



f= F00("name")
#當存在return object.__new__(cls)時,先後輸出Foo--new--和Foo--init--,說明__new__執行在__init__之前
#當去掉return object.__new__(cls)時,只輸出Foo--new--,說明__init__執行個體時沒有被執行個體
#總結:__new__方法是類裡面內建的,new是使用者來建立執行個體的,預設不寫,可以重寫
#作用:在執行個體化時會先於__init__執行,我們想在執行個體化之前




2.關於__call__

class MyType(type):
def __init__(self,what,bases=None,dict=None):
super(MyType, self).__init__(what,bases,dict)
def __call__(self, *args, **kwargs):
obj=self.__new__(self,*args, **kwargs)
self.__init__(obj)

class Foo(object):#底層是通過MyType類的 __init__方法實現的
__metaclass__ =MyType
def __init__(self,name):#底層是通過MyType類的__call__方法的self.__init__(obj)實現的
self.name = name
def __new__(cls, *args, **kwargs):
return object.__new__(cls)#底層是通過MyType類的__call__方法的obj=self.__new__(self,*args, **kwargs)實現的



obj=Foo("name")#執行建立Foo的執行個體其實是執行MyType類的__call__方法
#__call__作用時用於建立__new__的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.