Python中的 super() 方法设计目的是用来解决多重继承时父类的查找问题,一般我们在子类中需要调用父类的方法时才会这么用。
super(type[, object-or-type])
- 参数
– type: 类。
– object-or-type: 类,一般是 self
示例
Eg1.
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): # FooChild是FooParent的子类
def __init__(self):
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')
Out:
解析:
①fooChild = FooChild()
:先执行FooChild.__init__()
来初始化,然后super(FooChild,self). __init__ ()
则是调用FooParent.__init__()
,输出Parent,初始化下一句输出Child;
②fooChild.bar('HelloWorld')
:执行FooChild.bar()
,其中第一句super(FooChild, self).bar(message)
则又是调用FooParent.bar()
,输出HelloWorld from Parent
Eg2.
class C(A):
def m(self):
print('C')
super().m() #调用C的父类A的m()