Python Multiple Inheritance – Python MRO (Method Resolution Order)

Free Python courses with 57 real-time projects - Learn Python

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). At last, we will learn complications in Multiple Inheritance in Python Programming Language.

So, let’s start Python Multiple Inheritance Tutorial.

Python Multiple Inheritance

Python Multiple Inheritance

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.

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)

Output

True

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__

Output

(<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.

>>> Child.mro()

Output

[<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()

Output

[<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.

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

Output

1
>>> M.id

Output

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

Output

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()

Output

A

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

Python Interview Questions on Multiple Inheritance

  1. How do you achieve multiple inheritance in Python?
  2. When should we use multiple inheritance in Python?
  3. What are the advantages and disadvantages of Python multiple inheritance?
  4. What is Python multiple inheritance? Explain with an example.
  5. How does Python multiple inheritance work?

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.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

21 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.

      • Joel Croteau says:

        Expanding on this, the order is left-to-right, depth first, with the added caveat that classes in the MRO are guaranteed to appear after any classes that inherit from them, as well as after any classes listed before them in any inheritance list. So for example, if I have
        class W: pass
        class X: pass
        class Y : pass
        class Z: pass
        class A(X,Y): pass
        class B(Y,Z,W): pass
        class M(B,A,Z): pass
        M.mro()

        this results in
        [__main__.M,
        __main__.B,
        __main__.A,
        __main__.X,
        __main__.Y,
        __main__.Z,
        __main__.W,
        object]

        Because A inherits from Y, Y cannot appear before it in the MRO. Because Z appears after A in the inheritance list for M, it can’t appear before it in the MRO. Because W appears after Z in the inheritance list for B, it can’t appear before Z so both of those are pushed to the end. If on the other hand, we move W to the beginning of B’s inheritance list:
        class W: pass
        class X: pass
        class Y : pass
        class Z: pass
        class A(X,Y): pass
        class B(Y,Z,W): pass
        class M(B,A,Z): pass
        M.mro()

        then the output is
        [__main__.M,
        __main__.B,
        __main__.W,
        __main__.A,
        __main__.X,
        __main__.Y,
        __main__.Z,
        object]

        because there are no constraints on where W can be. It is incidentally an error to try to create a class hierarchy where this requirements can’t be met. So for example, if I have
        class D(X,Y): pass
        class E(Y,X): pass

        then trying
        class N(D,E): pass

        results in
        TypeError: Cannot create a consistent method resolution
        order (MRO) for bases X, Y

  6. Priyanka V says:

    Hi,

    class D(B,C):

    So the D should first refer Class B correct?? as its Super class, can we understand why its referring Class C?? resulting in below output :

    #output:
    # go A go!
    # go B go!
    # go D go!

    C shouldn’t be called at all correct??
    Please help.

    Thanks,
    Priyanka

    • DataFlair says:

      In this example we were showing hybrid inheritance (in this case it is combination of multiple and Hierarchical inheritance) which is why D is inheriting both B and C class.

  7. Nikhil says:

    Thankyou

  8. Arun says:

    In Case of Multiple Inheritance, how to inherit both the __init__methods of parent classes (say: A and B are both parent class) into a child class (say : c as child class inheriting from both A and B), using super().__init__() method.

    • DataFlair says:

      You can call A’s init method using “A.__init__(self)” abd B’s init method using “B.__init__(self)” inside C’s init method.

  9. Ajay Sharma says:

    I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.

  10. Hectic Badger says:

    You say that MRO uses left-right, depth first search, but on the directed acyclic graph (where you confusingly swap the order of B-A to A-B), a DFS would start M-B-Y-object. You have missed out a critical part of the algorithm that states “children come before parents” in the MRO.

  11. Ranu Shah says:

    Great Explanation python detail more, I can understand very clear viewpoint at all separation point . Thank you for post this courses . I would like to continue learning that courses different type.

    • DataFlair Team says:

      It’s truly heartening to see that our efforts have been significantly beneficial to you. Our team continuously work hard toward a better experience. You can also contribute us by sharing our article with as many as people.

Leave a Reply

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