Python中__init__()方法注意點

來源:互聯網
上載者:User

標籤:子類   hello   col   __name__   bsp   style   ret   www   c#   

此文轉自https://www.cnblogs.com/zyxstar2003/archive/2011/03/21/1989954.html

1、__init__並不相當於C#中的建構函式,執行它的時候, 執行個體已構造出來了
1 class A(object):2     def __init__(self,name):3         self.name=name4     def getName(self):5         return ‘A ‘+self.name

當我們執行

1 a=A(‘hello‘)

時,可以理解為

1 a=object.__new__(A)2 A.__init__(a,‘hello‘)

即__init__作用是初始化已執行個體化後的對象。

2、子類可以 不重寫__init__,執行個體化子類時, 會自動調用超類中已定義的__init__
1 class B(A):2     def getName(self):3         return ‘B ‘+self.name4  5 if __name__==‘__main__‘:6     b=B(‘hello‘)7     print b.getName()

但如果重寫了__init__,執行個體化子類時,則不會隱式的再去調用超類中已定義的__init__

1 class C(A):2     def __init__(self):3         pass4     def getName(self):5         return ‘C ‘+self.name6  7 if __name__==‘__main__‘:8     c=C()9     print c.getName()

則會報"AttributeError: ‘C‘ object has no attribute ‘name‘”錯誤,所以如果重寫了__init__,為了能使用或擴充超類中的行為,最好顯式的調用超類的__init__方法

1 class C(A):2     def __init__(self,name):3         super(C,self).__init__(name)4     def getName(self):5         return ‘C ‘+self.name6  7 if __name__==‘__main__‘:8     c=C(‘hello‘)    9     print c.getName()

 

Python中__init__()方法注意點

聯繫我們

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