Python 中 super( ) 的用法

super()也是很常用的一个函数了,我们在实现来自基类的子网时,经常会用到这个,比如说Convolution,RNN层的子网实现。

super()函数用于调用父类的一个方法,super()解决多重继承的问题,我们可以直接使用 类名.方法 继承,但是这种继承并不是最优的,并且需要在子类中修改代码,使用super()父类多次被调用时只执行一次,优化了执行逻辑。另外,使用多继承,会涉及到查找顺序问题等。

举个例子:

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % 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')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')
Parent
Child
HelloWorld from Parent
Child bar fuction


猜你喜欢

转载自blog.csdn.net/u012193416/article/details/81052328
今日推荐