In this lesson we want to learn about Python Multiple Inheritance, there are different inheritance types in Python Programming Language, for example we have multiple inheritance, multi level inheritance, hierarchical inheritance and hybrid inheritance, particularly in this article we want to learn 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](https://geekscoders.com/wp-content/uploads/2020/11/python-multiple-inheritance.jpg)
You can see that 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.
Now let’s create a practical example for Multiple Inheritance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class A: def a_method(self): print("A method from class A") class B: def b_method(self): print("B method from Class B") class C(A,B): pass c = C() c.a_method() c.b_method() |
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.
![Python Multiple Inheritance](https://geekscoders.com/wp-content/uploads/2020/11/python-multiple-inheritance-example.jpg)
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class A: def full_name(self): print("This is my full name - Class A") class B: def full_name(self): print("This is my full name - Class B") class C(B,A): pass c = C() c.full_name() |
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.
![Multiple Inheritance MRO](https://geekscoders.com/wp-content/uploads/2020/11/creating-multiple-inheritance-in-python.jpg)