Multiple Inheritance in Python

In this article we are going to talk about Multiple Inheritance in Python, so first of all

what is Multiple Inheritance in Python, if a class extends from more than one class,

that is called multiple inheritance.

 

 

Now let’s look at this image example.

Python Multiple Inheritance
Python Multiple Inheritance

 

 

In the above image we have three classes, Class A and Class B are our base class,

also we have another class that is Class C, now this Class C  extends from Class A

and Class B, as we have already said that if a class extends from more than one class,

that is called multiple inheritance. in here our C Class extends from two base classes,

now the C class can access to all attributes and methods of the Class A and Class B.

 

 

 

 

Let’s create a practical example for Multiple Inheritance.

 

In the above example we have two base classes and the third class is extending

from these two base class, and if you see in our base classes we have methods,

after extending Class C can access to these two methods.

 

 

Run the code and this is the result.

Multiple Inheritance in Python
Multiple Inheritance in Python

 

 

 

Let’s create another example, in this example we want to override a method in to

our base classes, also we are going to talk about Method Resolution Order (MRO).

 

You can see that when we are extending our Class C, we have the order of B and A,

now it will first check the method in the C class, if it does not find the method in the C class,

than it checks the B Class, now it means that the order matters in Python Multiple Inheritance,

if we run this code you will see that first we have our B Class method.

 

 

Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.

Leave a Comment