Python_有关继承_super()

该文取自:https://blog.csdn.net/wangxinsheng0901/article/details/82747781

super()在Python中常用于类的继承,相比于直接调用继承,采用super()可以保证父类不被重复调用。

对于简单的调用父类:

1 class parent:
2     def fun1(self,message):
3         print(message)
4 class child(parent):
5     def fun2(self,message):
6         parent.fun1(self,message)
7  
>>> child().fun2('hello')
   hello

对于上面的例子,如果当父类的名字修改后,子类中相应的名字也要进行修改。为了避免该问题,可通过super()解决

1 class parent:
2     def fun1(self,message):
3         print(message)
4 class child(parent):
5     def fun2(self,message):
6         super(child,self).fun1(message)
7  
>>> child().fun2('hello')
   hello

上面两个例子中super(child,self).fun1(message)和parent.fun1(self,message)的表现一致,不过当涉及到多继承情况时,两种调用方式就会产生差异:

 1 class A:
 2     def __init__(self):
 3         print('Enter A')
 4         print('Leave A')
 5 class B(A):
 6     def __init__(self):
 7         print('Enter B')
 8         A.__init__(self)
 9         print('Leave B')
10 class C(A):
11     def __init__(self):
12         print('Enter C')
13         A.__init__(self)
14         print('Leave C')
15 class D(B,C):
16     def __init__(self):
17         print ('Enter D')
18         B.__init__(self)
19         C.__init__(self)
20         print('Leave D')
21         
   >>> D()
     Enter D
     Enter B
     Enter A
    Leave A
     Leave B
     Enter C
     Enter A
     Leave A
     Leave C
     Leave D

下边是采用super()的情况,在super机制中可以保证公共父类仅被执行一次,且按照MRO(Method Resolution Order)进行:

 1 class A:
 2     def __init__(self):
 3         print('Enter A')
 4         print('Leave A')
 5 class B(A):
 6     def __init__(self):
 7         print('Enter B')
 8         super(B,self).__init__()
 9         print('Leave B')
10 class C(A):
11     def __init__(self):
12         print('Enter C')
13         super(C,self).__init__()
14         print('Leave C')
15 class D(B,C):
16     def __init__(self):
17         print ('Enter D')
18         super(D,self).__init__()
19         print('Leave D')
20         
21   >>> D()
22     Enter D
23     Enter B
24     Enter C
25     Enter A
26     Leave A
27     Leave C
28     Leave B
29     Leave D

 

posted @ 2019-05-16 09:53  Handsome_dj  阅读(144)  评论(0编辑  收藏  举报