美文网首页Python学习
python中的super() 函数

python中的super() 函数

作者: wangcc_sd | 来源:发表于2019-03-08 16:53 被阅读1次

super() 函数是用于调用父类(超类)的一个方法。

super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

# -*-coding:utf-8 -*-
# BY WANGCC

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent class---(1)')

    def bar(self,message):
        print ("%s from Parent def -----(2)" % message)

class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象
        super(FooChild,self).__init__()
#        print ('Child')

    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction    ---foochild ---bar(3)')
        print (self.parent,'foochild ---bar  ---()4')

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

ps:这个例子是讲的比较清楚的一个例子,如果还有什么疑问的话,可以用调试模式运行一遍就明白了、

相关文章

  • 怎么理解Python类中的super函数

    前言 在Python类的继承中,经常能看到super函数的存在,那super函数主要的作用,以及如何理解和使用好这...

  • python中的super() 函数

    super() 函数是用于调用父类(超类)的一个方法。 super 是用来解决多重继承问题的,直接用类名调用父类方...

  • python super()和classmethod

    @(python) super(type, obj) 子类中定义了同父类同名的函数后,需要显示调用父类函数时,可以...

  • python 神奇的super()

    我们都知道在python继承中,子类调用父类的方法是使用super()函数,在2.X里格式是super(mycla...

  • Python中super函数的使用

    super() 函数是用于调用父类(超类)的一个方法。self 始终为子类的实例 super 是用来解决多重继承问...

  • Python super() 函数

    描述 super() 函数是用于调用父类(超类)的一个方法。super 是用来解决多重继承问题的,直接用类名调用父...

  • Python super() 函数

  • Python super() 函数

    super() 函数用于调用下一个父类(超类)并返回该父类实例的方法。 super 是用来解决多重继承问题的,直接...

  • Python super() 函数

    描述 super() 函数是用于调用父类(超类)的一个方法。 super 是用来解决多重继承问题的,直接用类名调用...

  • Python:super函数

    这是个高大上的函数,在python装13手册里面介绍过多使用可显得自己是高手 23333. 但其实他还是很重要的....

网友评论

    本文标题:python中的super() 函数

    本文链接:https://www.haomeiwen.com/subject/yzarpqtx.html