super()方法

时间:2024-01-12 16:06:44

super()是一个调用父类的方法.

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

python2.x实例

class A(object):
pass class B(A):
def add(self, x):
super(B, self).add(x)

python3.x实例

class A:
pass class B(A):
def add(self, x):
super().add(x)

实例

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
I'm the parent.