Multiple Inheritance in Python - Letsprogram

Share:

Python supports a form of multiple inheritance as well. When a derived class has two or more parent class then it is exhibiting multiple inheritance. The syntax for multiple inheritance is :

class DerivedClass(base1,base2,base3):
      <statement 1>
      .
      .
     <statement n>

Python searches for attributes inherited from the parent class as left-right not searching in the same class twice.

Learn more about inheritance .

In multiple inheritance there in some cases it may exhibit diamond relationships where at least one of the parent class is accessed through multiple ways from the bottom-most class.

Let's take an example where a diamond relationship exists.

Diamond relationship in multiple inheritance


suppose there is a method name add in the class "Base1". Base2 and Base 3 class inherit from Base1 class if there is an overridden method add in the Base2 and Base3 then ambiguity arises which of the method add should we inherit into the class "Derived".



If the "Base2" class has no method add then it will check in Base3 class whether it has add method or not.

When every class defines the same method as having the same number of arguments than to use the base class method use the class name to access the method.





The output of the above code has one problem associated with it, the method m of Class1 is called twice. Python provides a solution to the above problem with the help of the super() function.


The super function will come to a conclusion about which method to execute by an order.

No comments

F