Search code examples
pythonmultiple-inheritancediamond-problem

What is the problem in this multiple inheritance?


class A:

    def __init__(self,name):
        self.name=name

class B(A):

    def __init__(self,name,add):
        super().__init__(name)
        self.add = add

class C(A):

    def __init__(self,name,tel):
        super().__init__(name)
        self.tel = tel

class D(B,C):

    def __init__(self,name,add,tel,company):
        super().__init__(name,add)
        super().__init__(name,tel)
        self.company = company

d = D('Hank','ctm',55514,'google')

enter image description here


Solution

  • A resolution to this multiple inheritance is to cooperatively design the classes, see Raymond's article Python’s super() considered super!:

    class A:
        def __init__(self, name, **kwargs):
            self.name = name
    
    class B(A):
        def __init__(self, add, **kwargs):
            super().__init__(**kwargs)
            self.add = add
    
    class C(A):
        def __init__(self, tel, **kwargs):
            super().__init__(**kwargs)
            self.tel = tel
    
    class D(B, C):
        def __init__(self, company, **kwargs):
            super().__init__(**kwargs)
            self.company = company
    
    d = D(name='Hank', add='ctm', tel=55514, company='google')
    

    As pointed out by others, this will follow the MRO, e.g. D -> B -> C - A.