super继承和普通继承

一。普通继承

>>> class A:
...     def __init__(self):
...             print 'Enter A'
...             print 'Leave A'
... 
>>> class B(A):
...     def __init__(self):
...             print 'Enter B'
...             A.__init__(self)
...             print 'Leave B'
... 
>>> class C(A):
...     def __init__(self):
...             print 'Enter C'
...             A.__init__(self)
...             print 'Leave C'
... 
>>> class D(A):
...     def __init__(self):
...             print 'Enter D'
...             A.__init__(self)
...             print 'Leave D'
... 
>>> class E(B,C,D):
...     def __init__(self):
...             print 'Enter E'
...             B.__init__(self)
...             C.__init__(self)
...             D.__init__(self)
...             print 'Leave E'
... 

  运行结果

>>> E()
Enter E
Enter B
Enter A
Leave A
Leave B
Enter C
Enter A
Leave A
Leave C
Enter D
Enter A
Leave A
Leave D
Leave E
<__main__.E instance at 0x108670560>
>>> 

二。super继承

>>> class A(object):
...     def __init__(self):
...             print 'Enter A'
...             print 'Leave A'
... 
>>> class B(A):
...     def __init__(self):
...             print 'Enter B'
...             super(B,self).__init__()
...             print 'Leave B'
... 
>>> class C(A):
...     def __init__(self):
...             print 'Enter C'
...             super(C,self).__init__()
...             print 'Leave C'
... 
>>> class D(A):
...     def __init__(self):
...             print 'Enter D'
...             super(D,self).__init__()
...             print 'Leave D'
... 
>>> class E(B,C,D):
...     def __init__(self):
...             print 'Enter E'
...             super(E,self).__init__()
...             print 'Leave E'
... 

 运行结果

>>> E()
Enter E
Enter B
Enter C
Enter D
Enter A
Leave A
Leave D
Leave C
Leave B
Leave E
<__main__.E object at 0x10513bc10>

三。结论

   除了代码简化了外,明白两者调用父类的次数和调用的顺序,其他不深入探讨.

posted @ 2017-11-24 12:42  Python++  阅读(185)  评论(0编辑  收藏  举报