python中的__init__ 、__new__、__call__等內建函數的剖析

來源:互聯網
上載者:User

標籤:

1.__new__(cls, *args, **kwargs)  

建立對象時調用,返回當前對象的一個執行個體;注意:這裡的第一個參數是cls即class本身
2.__init__(self, *args, **kwargs)

建立完對象後調用,對當前對象的執行個體的一些初始化,無傳回值,即在調用__new__之後,根據返回的執行個體初始化;注意,這裡的第一個參數是self即對象本身【注意和new的區別】
3.__call__(self,  *args, **kwargs)

如果類實現了這個方法,相當於把這個類型的對象當作函數來使用,相當於 重載了括弧運算子

#__conding:utf-8__class Person:    def __init__(self, name):        self.name = name    def sayHi(self):        print("Hello my name is:%s" %self.name)p = Person("wuyanlong")p.sayHi()class P(object):    def __init__(self, *args, **kwargs):        print "init"        super(P,self).__init__(*args, **kwargs)    def __new__(cls, *args, **kwargs):        print "new", cls        return super(P, cls).__new__(cls ,*args, **kwargs)    def __call__(self, *args, **kwargs):        print "call"pp = P()print "__________"pp()

運行結果:

***:~/Python爬蟲/class$ python calss1.py Hello my name is:wuyanlongnew <class ‘__main__.P‘>init__________call

 

4. __getattr__:

從對象中讀取某個屬性時,首先需要從self.__dicts__中搜尋該屬性,再從__getattr__中尋找。

class A(object):     def __init__(self):         self.name = ‘from __dicts__: zdy‘      def __getattr__(self, item):         if item == ‘name‘:             return ‘from __getattr__: zdy‘         elif item == ‘age‘:             return 26  a = A() print a.name # 從__dict__裡獲得的 print a.age # 從__getattr__獲得的

 

5. __setattr__

class A(object):    def __setattr__(self, *args, **kwargs):         print ‘call func set attr‘         return object.__setattr__(self, *args, **kwargs) 

 

 

6. __delattr__

函數式用來刪除對象的屬性:

class A(object):    def __delattr__(self, *args, **kwargs):         print ‘call func del attr‘         return object.__delattr__(self, *args, **kwargs)  

 

python中的__init__ 、__new__、__call__等內建函數的剖析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.