Python multiple inheritance constructor not called when using super()

前端 未结 2 715
我寻月下人不归
我寻月下人不归 2021-01-13 06:54

Consider the following code:

class A(object):
    def __init__(self):
        pass
class B(object):
    def __init__(self):
        self.something = \'blue\'         


        
2条回答
  •  -上瘾入骨i
    2021-01-13 07:13

    As others have mentioned, the method resolution order is key here. If you want to call multiple superclass constructors, then you will have to call them directly.

    class A(object):
        def __init__(self):
            pass
    class B(object):
        def __init__(self):
            self.something = 'blue'
        def get_something(self):
            return self.something
    class C(A,B):
        def __init__(self):
            A.__init__(self)
            B.__init__(self)
            print(self.get_something())
    

提交回复
热议问题