物件導向的核心為對象,對象是由類執行個體化而來的,那麼類與類之間存在一個繼承的關係,被繼承的類叫做父類,繼承了父類的類為子類。
子類繼承了父類,那麼子類執行個體化的對象就可以調用所有父類的方法,當然也可以調用子類自身所有的方法。因為這些方法都屬於該對象的方法。
比如,子類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指的就是子類執行個體。