python中子類執行個體化調用父類方法

來源:互聯網
上載者:User

物件導向的核心為對象,對象是由類執行個體化而來的,那麼類與類之間存在一個繼承的關係,被繼承的類叫做父類,繼承了父類的類為子類。

子類繼承了父類,那麼子類執行個體化的對象就可以調用所有父類的方法,當然也可以調用子類自身所有的方法。因為這些方法都屬於該對象的方法。

比如,子類child繼承了父類father

child.py

from father import fatherclass child(father):    def childprint(self):        print "this is a child"

father.py

class father:    def common(self):        print "this is a father also common"

那麼當子類的一個執行個體test = child()可以調用父類的common()方法,如下所示:

third.py

from child import childtest = child()test.common()

則運行third.py的結果為:


但如果我們將father.py的檔案做如下修改:

father.py

class father:    def common(self):        print "this is a father also common"        self.childprint()


則執行的結果如下:


可以看到,“this is a child”也被列印了。很明顯我們子類的一個執行個體調用了父類的common方法,而該方法裡居然調用了子類的childprint方法。這是怎麼回事。

事實是這樣子的,前面說過,子類執行個體化後,所有子類繼承的父類的方法以及子類自身的方法都歸該執行個體所有,那麼此時的common方法自然是屬於子類剛才執行個體化的對象,

所有自然可以在common方法中調用子類的childprint方法。表面上看是父類調用子類方法,其實還是子類執行個體調用自己的方法。self.childprint()中的self指的就是子類執行個體。

聯繫我們

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