Python Multiple Inheritance – Python MRO (Method Resolution Order)

1. Python Multiple Inheritance & MRO

In our last article, we discussed Python inheritance. Here, Python Multiple Inheritance tutorial, we will discuss what is Multiple inheritances in Python with its examples and uses. On the other hand, we will learn Python MRO (Method Resolution Order). Atlast, we will learn complications in Multiple Inheritance in Python Programming Lanaguge.

So, let’s start Python Multiple Inheritance Tutorial.

Python Multiple Inheritance

Python Multiple Inheritance

2. What is Python Multiple Inheritance?

As its name is indicative, multiple inheritance in python is when a class inherits from multiple classes. One example of this would be that a child inherits personality traits from both parents.

Python Multiple Inheritance - Example

Python Multiple Inheritance – Example

Before we proceed to multiple inheritance syntaxes, let’s see the python syntax.

3. Python Multiple Inheritance Syntax

To make a class inherit from multiple python classes, we write the names of these classes inside the parentheses to the derived class while defining it. We separate these names with commas.
The code for the previous example would be:

>>> class Mother:
                pass
>>> class Father:
                pass
>>> class Child(Mother,Father):
                pass
>>> issubclass(Child,Mother) and issubclass(Child,Father)

True

4. Python MRO (Method Resolution Order)

When we search for an attribute in a class that is involved in python multiple inheritance, an order is followed. First, it is searched in the current class. If not found, the search moves to parent classes. This is left-to-right, depth-first.

So, in the above class, the search order will be – Child, Mother, Father, Object.

This order is called linearization of class Child, and the set of rules applied are called MRO (Method Resolution Order). To get the MRO of a class, you can use either the __mro__ attribute or the mro() method.

>>> Child.__mro__

(<class ‘__main__.Child’>, <class ‘__main__.Mother’>, <class ‘__main__.Father’>, <class ‘object’>)
The __mro__ attribute returns a tuple, but the mro() method returns a python list.

Join DataFlair on Telegram
>>> Child.mro()
[<class ‘__main__.Child’>, <class ‘__main__.Mother’>, <class ‘__main__.Father’>, <class ‘object’>] To take a more complex example that also demonstrates depth-first search, we take 6 classes.

>>> class X:pass
>>> class Y: pass
>>> class Z:pass
>>> class A(X,Y):pass
>>> class B(Y,Z):pass
>>> class M(B,A,Z):pass
>>> M.mro()
[<class ‘__main__.M’>, <class ‘__main__.B’>, <class ‘__main__.A’>, <class ‘__main__.X’>, <class ‘__main__.Y’>, <class ‘__main__.Z’>, <class ‘object’>] We can represent this with the following diagram.

Python Multiple Inheritance - Method Resolution order (MRO)

Python Multiple Inheritance – Method Resolution order (MRO)

First, the interpreter scans M. Then, it scans B, and then A-B first because of the order of arguments at the time of inheritance. It scans Z later, after X and Y. The order is- X, then Y, then Z. This is because due to depth-first search, X comes first to A. Finally, it scans the class object. Hence, the order.

Python Interview Questions

5. Complications in Python Multiple Inheritance

What happens when the classes we inherit from all have a common attribute? Whose value does the child class take, then? Let’s take three classes A, B, and C.

>>> class A:
                id=1            
>>> class B:
                id=2             
>>> class C:
                id=3              
>>> class M(A,C,B):
                pass
>>> M.id

1

>>> M.id

1

>>> class M(C,B,A):
                pass
>>> M.id

3
Like we see here, the class named first in the inheritance passes its value to the child class for the common attribute. Earlier, it was A, so, M had id=1. Then, when we changed it to C, M got id=3. This is the same with Python methods/functions of the class.

>>> class A:
                def sayhi():
                                print("A")                          
>>> class B:
                def sayhi():
                                print("B")                         
>>> class M(A,B):
                pass
>>> M.sayhi()

A

So, this was all about Python Multiple Inheritance Tutorial. Hope you like our explanation on Python MRO.

6. Conclusion

Hence, in this tutorial, we discussed python multiple inheritances and its syntax and examples. We also talked about Method Resolution Order(MRO) and last we discuss, complications in multiple inheritances in python. Keep going with us in Python and give us your valuable feedbacks.
Top books for Learning python.
For reference

10 Responses

  1. Nitesh Rawat says:

    Hi,
    I really enjoyed this clear explanation of multiple inheritance and MRO. Great job!
    I have a question/problem regarding super and MRO.please provide an email id for me to post it. Thanks in advance 🙂

  2. Nitesh Rawat says:

    Hi team,
    Can you please help me explain the output of the below code:
    class A(object):
    def go(self):
    print(“go A go!”)
    def stop(self):
    print(“stop A stop!”)
    def pause(self):
    raise Exception(“Not Implemented”)
    class B(A):
    def go(self):
    super(B, self).go()
    print(“go B go!”)
    class C(A):
    def go(self):
    super(C, self).go()
    print(“go C go!”)
    def stop(self):
    super(C, self).stop()
    print(“stop C stop!”)
    class D(B,C):
    def go(self):
    super(D, self).go()
    print(“go D go!”)
    def stop(self):
    super(D, self).stop()
    print(“stop D stop!”)
    def pause(self):
    print(“wait D wait!”)
    class E(B,C): pass
    #Driver run :
    d = D()
    d.go()
    #output:
    # go A go!
    # go C go!
    # go B go!
    # go D go!

    • DataFlair Team says:

      Hello Nitesh,

      Thanks for commenting and for the query on Python Multiple Inheritance.
      In your code, you first instantiate class D. This gives us the object d.
      On this, you call the method go().

      This brings us to the following part of your code:

      def go(self):
      super(D, self).go()
      print(‘go D go!’)

      Here, this makes a call to super(D,self).go()
      This means it first makes a call to go() in C, and then in B.
      This lands us at this part of your code:

      def go(self):
      super(C, self).go()
      print(‘go C go!’)

      Now, this makes a call to super().go() of class A. This brings us to:

      def go(self):
      print(‘go A go!’)

      This prints “go A go!”
      Coming back to the call for go() in C and:
      This prints “go C go!”

      Then, this gets back to the call to go() in B and:
      This prints “go B go!”
      Finally, this gets to the parent call to go() in D and:
      This prints “go D go!”

      Here you go. For more queries, you can post a comment on that particular Python tutorial.
      Enjoy coding Python!

  3. Kuman says:

    Explanaion is really very good.

  4. Mike says:

    Thanks for sharing python multiple inheritances tutorial details, such a great way to present the information. I have read your blogs they are very nice

    • DataFlair Team says:

      Hey Mike,
      Thanks for such nice words; our team continuously works toward a better reader experience. You can also contribute to DataFlair by sharing our article in your peer groups.

  5. shubham says:

    Hi Team, I need a small clarification on
    this MRO example
    >>> class X:pass
    >>> class Y: pass
    >>> class Z:pass
    >>> class A(X,Y):pass
    >>> class B(Y,Z):pass
    >>> class M(B,A,Z):pass

    Here in class M(B,A,Z), first B gets executed, but B has in turn Y and Z. Why are they not being called as in case of A, where X and Y are ?

    • Mulagala says:

      It will check for the good head(which means does the class B inheriting from any of the classes which are called later, If yes then they will not added to the current search list). Here when it is checks for the B, It has two parent classes which are actually called later(Y from class A, and Z from class M), So they will not added in the search list when it checks for B.

    • Mulagala says:

      HI Shubham,

      It will check for the good head(which means does the class B inheriting from any of the classes which are called later, If yes then they will not added to the current search list). Here when it is checks for the B, It has two parent classes which are actually called later(Y from class A, and Z from class M), So they will not added in the search list when it checks for B.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.