描述:
super()函数用于调用父类(超类)的一个方法。
super()函数是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没有问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO就是类等方法解析顺序表,其实也就是继承父类方法时的顺序表。
语法:
以下是super()方法的语法:
super(type[object-or-type])
参数:
实例:
1 class FooParent(object): 2 def __init__(self): 3 self.parent = ‘I\‘m the parent.‘ 4 print(‘Parent‘) 5 6 def bar(self,message): 7 print("%s from Parent" % message) 8 9 class FooChild(FooParent): 10 def __init__(self): 11 # super() 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象 12 super().__init__() 13 print(‘Child‘) 14 15 def bar(self,message): 16 super().bar(message) 17 print(‘Child bar function‘) 18 print(self.parent) 19 20 if __name__ == ‘__main__‘: 21 fooChild = FooChild() 22 fooChild.bar(‘helloworld‘)
原文:https://www.cnblogs.com/helloTerry1987/p/10991481.html