标签:顺序 深度优先 理解 obj python3 method order tar eth
super()函数可以用于继承父类的方法,语法如下:
super(type[, object-or-type])
虽然super()函数的使用比较简单,但是需要根据单继承和多继承来分析函数的调用关系。
首先,当类之间的继承关系为单继承时,函数调用关系也比较简单,可以参考如下的例子:
1 #!/usr/bin/env python3 2 3 class A(object): 4 def __init__(self): 5 print(‘class A‘) 6 7 class B(A): 8 def __init__(self): 9 super(B, self).__init__() 10 print(‘class B‘) 11 12 b = B()
上述代码运行结果如下:
class A class B
从结果可以看出,子类B在实例化时调用了父类A的__init__()方法。
当进行多重继承时,需要考虑MRO的问题。所谓MRO,即Method Resolution Order,自Python2.3以来,MRO采用广度优先(区别于深度优先)的规则定义。为了更好的理解这个问题,让我们先来看如下的代码:
1 #!/usr/bin/env python3 2 3 class A(object): 4 def __init__(self): 5 self.n = 10 6 7 def minus(self, m): 8 print(‘minus in class A start‘) 9 self.n -= m 10 print(‘minus in class A end‘) 11 12 class B(A): 13 def __init__(self): 14 self.n = 7 15 16 def minus(self, m): 17 print(‘minus in class B start‘) 18 super(B, self).minus(m) 19 self.n -= 2 20 print(‘minus in class B end‘) 21 22 class C(A): 23 def __init__(self): 24 self.n = 12 25 26 def minus(self, m): 27 print(‘minus in class C start‘) 28 super(C, self).minus(m) 29 self.n -= 5 30 print(‘minus in class C end‘) 31 32 class D(B,C): 33 def __init__(self): 34 self.n = 15 35 36 def minus(self, m): 37 print(‘minus in class D start‘) 38 super(D, self).minus(m) 39 self.n -= 2 40 print(‘minus in class D end‘) 41 42 print(‘The MRO of class D is :‘) 43 print(D.__mro__) 44 45 d = D() 46 d.minus(2) 47 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,而后续的调试打印信息也正好验证了该顺序。
标签:顺序 深度优先 理解 obj python3 method order tar eth
原文地址:https://www.cnblogs.com/zhouxingyu1993/p/12825968.html