千锋 2020-05-04
super()函数可以用于继承父类的方法,语法如下:
super(type[, object-or-type])
虽然super()函数的使用比较简单,但是需要根据单继承和多继承来分析函数的调用关系。
首先,当类之间的继承关系为单继承时,函数调用关系也比较简单,可以参考如下的例子:
#!/usr/bin/env python3 class A(object): def __init__(self): print(‘class A‘) class B(A): def __init__(self): super(B, self).__init__() print(‘class B‘) b = B()
上述代码运行结果如下:
class A class B
从结果可以看出,子类B在实例化时调用了父类A的__init__()方法。
当进行多重继承时,需要考虑MRO的问题。所谓MRO,即Method Resolution Order,自Python2.3以来,MRO采用广度优先(区别于深度优先)的规则定义。为了更好的理解这个问题,让我们先来看如下的代码:
#!/usr/bin/env python3 class A(object): def __init__(self): self.n = 10 def minus(self, m): print(‘minus in class A start‘) self.n -= m print(‘minus in class A end‘) class B(A): def __init__(self): self.n = 7 def minus(self, m): print(‘minus in class B start‘) super(B, self).minus(m) self.n -= 2 print(‘minus in class B end‘) class C(A): def __init__(self): self.n = 12 def minus(self, m): print(‘minus in class C start‘) super(C, self).minus(m) self.n -= 5 print(‘minus in class C end‘) class D(B,C): def __init__(self): self.n = 15 def minus(self, m): print(‘minus in class D start‘) super(D, self).minus(m) self.n -= 2 print(‘minus in class D end‘) print(‘The MRO of class D is :‘) print(D.__mro__) d = D() d.minus(2) print(d.n)
代码运行结果:
The MRO of class D is : (<class ‘__main__.D‘>, <class ‘__main__.B‘>, <class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘object‘>) minus in class D start minus in class B start minus in class C start minus in class A start minus in class A end minus in class C end minus in class B end minus in class D end 4
从运行结果可以看出,子类D的MRO为(<class ‘__main__.D‘>, <class ‘__main__.B‘>, <class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘object‘>),也就是子类D的minus函数在调用父类函数时的调用顺序依次为BCA,而后续的调试打印信息也正好验证了该顺序。