0

I have doubt if multiple classes inherited to a derived class. How can we call the init of all base classes.

class Base1(object):
    def __init__(self):
        print('Constructor of Base1 Class')

class Base2(object):
    def __init__(self):
        print('Constructor of Base2 Class')

class Base3(object):
    def __init__(self):
        print('Constructor of Base3 Class')

class Derived(Base1, Base2, Base3):
    def __init__(self):
        super(Derived, self).__init__()
        print('Constructor of Derived Class')

if __name__ == '__main__':
   inst = Derived()

When i run the above code. I get the output as below

Constructor of Base1 Class
Constructor of Derived Class

I think Base2 and Base3 __init__ are not getting called. Is there a way to do it

0

2 Answers 2

2

You need to call super() in each constructor so that it calls __init__() from list of _mro_

class Base1(object):
    def __init__(self):
        super().__init__()
        print('Constructor of Base1 Class')

class Base2(object):
    def __init__(self):
        super().__init__()
        print('Constructor of Base2 Class')

class Base3(object):
    def __init__(self):
        super().__init__()
        print('Constructor of Base3 Class')

class Derived(Base1, Base2, Base3):
    def __init__(self):
        #  super(Derived, self).__init__()
        super().__init__()
        print('Constructor of Derived Class')

if __name__ == '__main__':
   inst = Derived()


Constructor of Base3 Class
Constructor of Base2 Class
Constructor of Base1 Class
Constructor of Derived Class
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, i have implemented this. But accepted Elya Fadeeva as answer, bcoz the help link he provided gave me much more infor in inheritance.
1

I think it is a proper way to do it:

class Base1(object):
    def __init__(self):
        print('Constructor of Base1 Class')

class Base2(object):
    def __init__(self):
        print('Constructor of Base2 Class')

class Base3(object):
    def __init__(self):
        print('Constructor of Base3 Class')

class Derived(Base1, Base2, Base3):
    def __init__(self):
        Base1.__init__(self)
        Base2.__init__(self)
        Base3.__init__(self)
        print('Constructor of Derived Class')

Output:

inst = Derived()
Constructor of Base1 Class
Constructor of Base2 Class
Constructor of Base3 Class
Constructor of Derived Class

Source: https://www.journaldev.com/14623/python-multiple-inheritance

1 Comment

Accepting yours as answer as you have also provided a link which explained more about the inheritance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.