0

I am new to python and trying to understand the inheritance in python. Python has a feature of multiple inheritance. A single class can inherit more than one class at a same time. When we create an object of child class,the init function of child class is called. I want to call the init function of both the parent class of the child, but i am able to call only only one init function.I read the concept of method resolution order, by which the left most class inherited init function will be called. Please correct my code, so that the init function of both parent classes is called.

class A:
    def __init__(self):
        print("in A Init")
    

class B:
    def __init__(self):
        print("in B Init")

    


class C(B,A):
    def __init__(self):
        super().__init__()
        print("in C Init")

cObj= C()

1 Answer 1

3

All the __init__ functions need to call super().__init__(), like this:

class A:
    def __init__(self):
        super().__init__()
        print("in A Init")

class B:
    def __init__(self):
        super().__init__()
        print("in B Init")

class C(B, A):
    def __init__(self):
        super().__init__()
        print("in C Init")

c_obj= C()

When you invoke this you get the following output:

in A Init
in B Init
in C Init

Per the super() function documentation, it returns a reference to "a parent or sibling" of the class, whichever is next in the method resolution order. At the top of the hierarchy, it returns a reference to the implicit parent class object, which has an empty __init__ method which does nothing.

In order for this to work well, it's best for all the inherited __init__ functions to have the same signature, including the common base class; in this case, the signature is just __init__(self) (no additional arguments), and the common base class is object, which also has __init__(self) with no additional arguments, so that's all good. Another common pattern is for them all to take keyword arguments and pass through **kwargs to the next one.

Sign up to request clarification or add additional context in comments.

2 Comments

The solution works.The super().__init__() function executes the init function of the parent class. But why we are putting the super().__init__() in the parent class ?
Explanation added to the answer; basically, the super() is not really "parent" but rather "next class in the inheritance graph"; in the simplest case that's the parent, but here it can also be sibling. At the top of the graph, it's the built-in object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.