python 中 __init__方法

來源:互聯網
上載者:User

標籤:getname   obj   錯誤   star   new   .com   def   pytho   sel   

注意1,__init__並不相當於C#中的建構函式,執行它的時候,執行個體已構造出來了。

class  A(object):    def  __init__(self,name):        self.name=name    def getName(self):        return ‘A‘ +self.name

 當我們執行

a=A("hello")

 時,可以理解為:

a=object.__new__(A)A.__init__(a,‘Hello‘)

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

注意2、子類可以不重寫__init__,執行個體化子類時,會自動調用超類中已定義的__init__

class  B(A):    def  getName(self):        return  ‘B‘+self.nameif  __name__=="__main__":    b=B(‘hello‘)    print  b.getName()

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

class C(A):    def __init__(self):         pass    def  getName(self):        return ‘C‘+self.nameif  __name__==‘__main__‘:    c=C()    print  c.getName()

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

class C(A):    def __init__(self,name):        super(C,self).__init__(name)    def getName(self):        return ‘C ‘+self.name if __name__==‘__main__‘:    c=C(‘hello‘)        print c.getName()

 

 

 

 

 

轉自:http://www.cnblogs.com/zyxstar2003/archive/2011/03/21/1989954.html

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.