NikoNyrh NikoNyrh - 4 months ago 19
Python Question

Call resolution order in Python with multiple inheritance

I was watching a Python talk at Youtube and found an interesting language feature. However when I tried to run a test code it didn't work and I'd like to understand why.

I was expecting this to print this:

Parent
OtherParent


But instead I got this:

Parent
Parent


Sample code:

class Parent:
def get_message(self):
return "Parent"

class Child(Parent):
def do_print(self):
print(super().get_message())

class OtherParent:
def get_message(self):
return "OtherParent"

class OtherChild(Child, OtherParent):
pass

Child().do_print()
OtherChild().do_print()


Edit: Running on Windows, Python 3.5.1, Anaconda 4.0.0 (64-bit)

Answer

If OtherParent does not inherit from Parent, it does not have the do_print method. Thus in this case the do_print defined in Parent is called twice.

Once OtherParent inherits from Parent, the do_print method of OtherParent is now called, thus the get_message method of OtherParent.

To sum up with some code:

Case 1

class OtherParent:
    def get_message(self):
        return "OtherParent"

class OtherChild(Child, OtherParent):
    pass

Child().do_print() # do_print comes from Parent
OtherChild().do_print() # do_print comes from Parent

Case 2

class OtherParent(Parent):
    def get_message(self):
        return "OtherParent"

class OtherChild(Child, OtherParent):
    pass

Child().do_print() # do_print comes from Parent
OtherChild().do_print() # do_print comes from OtherParent