Python - Calling __init__ for multiple parent classes

前端 未结 2 1319
清酒与你
清酒与你 2021-01-25 18:46

Edit: I am on Python 3.

I have a class X that extends both Y and Z:

class X(Y, Z):
    def __ini         


        
2条回答
  •  Happy的楠姐
    2021-01-25 19:03

    Generally there is no other way then to call Y.__init__(self) and Z.__init__(self) directly. It's the only way to ensure that both constructors are called at least once.

    However in some weird (or normal, depending on how you look at it) cases this can lead to very unintuitive results where base constructors are called multiple times:

    class Y:
        def __init__(self):
            print('Y')
            super().__init__()
    
    class Z:
        def __init__(self):
            print('Z')
            super().__init__()
    
    class X(Y, Z):
        def __init__(self):
            print('X')
            Y.__init__(self)
            Z.__init__(self)
    
    X()
    

    Results in

    X
    Y
    Z
    Z
    

    So in that case super().__init__() in X (instead of both .__init__() calls) seems natural and will work correctly. However it will fail if Y and Z don't call super().__init__() as well. In that case you will only call one of the constructors.

    So generally there is no way to solve your issue correctly without knowing implementation of base classes.

    YARtAMI = Yet Another Reason to Avoid Multiple Inheritance

提交回复
热议问题