python中子类实例化调用父类方法

来源:互联网 发布:白夜追凶网络剧 编辑:程序博客网 时间:2024/06/05 02:27

面向对象的核心为对象,对象是由类实例化而来的,那么类与类之间存在一个继承的关系,被继承的类叫做父类,继承了父类的类为子类。

子类继承了父类,那么子类实例化的对象就可以调用所有父类的方法,当然也可以调用子类自身所有的方法。因为这些方法都属于该对象的方法。

比如,子类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指的就是子类实例。

0 0
原创粉丝点击