Hybrid Inheritance in Python

Viewed 2982

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?

1 Answers

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.

Related