2

I am trying to implement multiple hybrid inheritance in python, it is giving answer also but I am wondering what is the reason behind the sequence of the answer, for this code:

class GrandPa:
    def __init__(self):
        print("Grand Pa")

class Father(GrandPa):
    def __init__(self):
        super().__init__()
        print("Father")

class Mother(GrandPa):
    def __init__(self):
        super().__init__()
        print("Mother")


class child(Father, Mother):
    def __init__(self):
        super().__init__()
        print("Child")

c = child()

OUTPUT

Grand Pa
Mother
Father
Child

In the child class we have taken Father class before the mother, so shouldn't Father be printed before Mother? Is there any logic behind this sequence?

2

1 Answer 1

2

You can always consult __mro__ to find out what is going on:

print(c.__class__.__mro__)
# (<class '__main__.child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class '__main__.GrandPa'>, <class 'object'>)

And indeed Father is coming before Mother in this chain.

But, when you are chaining calls like this, that's what actually happens:

class GrandPa:
    def __init__(self):
        print("Grand Pa")

class Father(GrandPa):
    def __init__(self):
        print('f', super())
        super().__init__()
        print("Father")

class Mother(GrandPa):
    def __init__(self):
        print('m', super())
        super().__init__()
        print("Mother")


class child(Father, Mother):
    def __init__(self):
        print('c', super())
        super().__init__()
        print("Child")

c = child()

I have added print(super()) to all methods to illustrate what is going on inside the callstack:

c <super: <class 'child'>, <child object>>
f <super: <class 'Father'>, <child object>>
m <super: <class 'Mother'>, <child object>>
Grand Pa
Mother
Father
Child

As you can see, we start with the Child, then go to Father, then to Mother, and only after that GrandPa is executed. Then the controll flow is returned to Mother and only after it goes to Father again.

In real life use-cases, it is not recommended to overuse the multiple inheritance. It might be a huge pain. Composition and mixins are way easier to comprehend.

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

Comments

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.