In this tutorial, we will discuss Python multiple inheritance and also code a program for it. We will also learn the multi-level inheritance.
Multiple Inheritance in Python
Multiple inheritance is a concept of Inheritance in which a derived class can inherit from more than one Base class.
It is a very powerful property of inheritance and comes very handy when we work on a big project, with the help of Multiple inheritance a class can inherit more than one base class.
class base_1: #base_1 block class base_2: # base_2 block class derived(base_2, base_1): #base derived block
Multiple inheritance example:
class Boy: def __init__(self): super().__init__() self.boy_Name= "John" def get_boy_Name(self): return self.boy_Name class Girl: def __init__(self): super().__init__() self.girl_name="Richa" def get_girl_Name(self): return self.girl_name class Call(Boy, Girl): def __init__(self): super().__init__() C1 = Call() print(C1.get_boy_Name()) print(C1.get_girl_Name())
Behind the Code:
Here in the above example, we have used super().__init__() function to initialize all the classes at once. And like inheritance in multiple inheritance, we have used the derived class to access it’s all base classes functions.
Multi-inheritance is similar as Multiple inheritances but the only difference is, in Multiple inheritance this is only one derive class to inherit from multiple base classes but in Multi-level inheritance a derive class inherit from another derived class.
Multi-level Inheritance Syntax
class base: # base class class derived_1(base): # first derived class class derived_2(derived_1): # inheriting from derived class
Method Resolution Order
Method of Resolution also known as MRO it describes the behavior of the child class object, and tell in which order the child class object will call the parent class methods and attributes.
class B: def b(self): print('b') def k(self): print("b's k") class C: def c(self): print('c') def k(self): print("c's k") class D(B, C): def d(self): print('d') d = D() d.b() d.c() d.d() d.k()
b c d b's k
Behind the code:
In the above example, we inherit class B and C in class D, and when we create the object of class D so, we get the authority to call the methods of B and C using the D object because we have inherited them.
You can see that B and C both contain a method with the same name k(self), printing different outputs but when we use the D object and call that k() method, only the Class B method gets executed not class C why? This is because of MRO (method resolution order).
When we call d.k(), the object first search the method k() in its own class which is class D then it went to class B and there it finds k() method.
What if class B did not have method k()?
then the object d would look in class C for it.
What if class B and C both did not have method k().
the object d would start to look in python built-in methods and if the Python built-in method did not have k() method then it would throw an error.