Search code examples
pythonoopinheritancesuperclass

how to use super().__init__() method for 2 or more classes?


Here I have provided an example to illustrate my problem when a class inherits from 2 classes, then the super method only calls the constructor of the first inherited class.

import inspect
class A :
    def __init__(self):
        self.atr1 = 'Foo1'

class B :
    def __init__(self):
        self.atr2 = 'Foo2'
        
class C(A,B) :
    def __init__(self) -> None:
        super().__init__()

## This part is only for illustration purpose
fooObj = C()
for i in inspect.getmembers(fooObj):
    if not i[0].startswith('_'):
        if not inspect.ismethod(i[1]):
            print(i)

Output: ('atr1', 'Foo1')

Can someone please fix it in a way so that both constructors from A and B being called? Note:

  • I don't want to hardcode class A and B in C
  • Class A and B are independent and don't inherit from each other

Solution

  • Call super().__init__() in all the classes:

    class A :
        def __init__(self):
            self.atr1 = 'Foo1'
            super().__init__()
    
    class B :
        def __init__(self):
            self.atr2 = 'Foo2'
            super().__init__()
            
    class C(A,B) :
        def __init__(self) -> None:
            super().__init__()
    

    This will cause C to call all __init__ in its MRO, up to the object class empty init.