Super init vs. parent.__init__

后端 未结 2 1000
不思量自难忘°
不思量自难忘° 2021-01-31 16:37

A Python subclass can be initialized with or without a call to super(), as shown below

class Parent(object):
    ...

class Child(Parent):

    def          


        
2条回答
  •  旧巷少年郎
    2021-01-31 17:02

    The purpose of super is to handle inheritance diamonds. If the class inheritance structure uses only single-inheritance, then using super() will result in the same calls as explicit calls to the "parent" class.

    Consider this inheritance diamond:

    class A(object):
        def __init__(self):
            print('Running A.__init__')
            super(A,self).__init__()
    
    class B(A):
        def __init__(self):
            print('Running B.__init__')        
            super(B,self).__init__()
    
    class C(A):
        def __init__(self):
            print('Running C.__init__')
            super(C,self).__init__()
    
    class D(B,C):
        def __init__(self):
            print('Running D.__init__')
            super(D,self).__init__()
    
    foo = D()
    

    which prints

    Running D.__init__
    Running B.__init__
    Running C.__init__
    Running A.__init__
    

    while if we change B to B2 and use explicit calls to the parent __init__:

    class B2(A):
        def __init__(self):
            print('Running B.__init__')        
            A.__init__(self) 
    
    class D2(B2,C):
        def __init__(self):
            print('Running D.__init__')
            super(D2,self).__init__()
    
    bar = D2()
    

    then the chain of init calls becomes

    Running D.__init__
    Running B.__init__
    Running A.__init__
    

    So the call to C.__init__ is skipped entirely.


    There is no one preferred option.

    If you can guarantee that you do not want to support multiple inheritance then explicit parent calls are simpler and clearer.

    If you wish to support multiple inheritance now or in the future, then you need to use super(). But understand that there are some pitfalls involved with using super, but with proper use these pitfalls can be avoided.

提交回复
热议问题