[Python Core] – Method Resolution Order (MRO) in Python OOP

Unlike Java which only has single inheritance, Python has multiple-inheritance. So the issue is how you would know the order of inheritance. The answer is simple (hopefully this post today is super short as well). Let’s make some code:

class Parent:
    def do_something(self):
        print("METHOD IN CLASS Parent")

class Child_A(Parent):
    def do_something(self):
        print("METHOD IN CLASS Child_A")

class Child_B(Parent):
    def do_something(self):
        print("METHOD IN CLASS Child_B")

class Grand_Child(Child_A, Child_B):
    pass


foo = Grand_Child()
foo.do_something()
  • Child_A and Child_B inherited from Parent
  • Grand_Child multiple-inherited from Child_A and Child_B

So if I called method do_something(), where does it come from? Parent, Child_B, or Child_A? This is the Output

METHOD IN CLASS Child_A

Well, if you’re familiar with multiple-inheritance in Python OOP, you might know Child_A should be priority, then comes to Child_B, and finally grand parent. But in case there are super multiple inheritances, how would you solve it? Then use mro (method resolution order). There are two typical ways to use it:

print(Grand_Child.mro())

Run the file, and the result is:

[<class '__main__.Grand_Child'>, <class '__main__.Child_A'>, <class '__main__.Child_B'>,
<class '__main__.Parent'>, <class 'object'>]

You might see the order of inheritance, but if it’s still not clear, then use:

help(Grand_Child)

Now the output seems much clearer:

Help on class Grand_Child in module __main__:

class Grand_Child(Child_A, Child_B)
| Method resolution order:
| Grand_Child
| Child_A
| Child_B
| Parent
| builtins.object
|
| Methods inherited from Child_A:
|
| do_something(self)

Hope that it helps.

Happy Coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *