Open Source Your Knowledge, Become a Contributor

Multiple Inheritance

Multiple Inheritance with two non overlapping parents

Multiple Inheritance is easy if we inherit from two parent class, each without any overlapping methods

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

classFather:

print("In Father")

deffuncA(self):

print('In funcA')

classMother:

print("In Mother")

deffuncB(self):

print('In funcB')

classSon(Father, Mother):

print("I am son")

x=Son()

x.funcA()

x.funcB()

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Multiple Inheritance with overlapping methods

If there are overlapping methods, the method of first parent class will be called. In the below example, since we added the class Father as the first argument in class Son(Father, Mother), the method in class Father will be called. If it had been class Son(Mother, Father) then method in class Mother will be called.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

classFather:

print("In Father")

deffuncA(self):

print('In Father funcA')

classMother:

print("In Mother")

deffuncA(self):

print('In Mother funcA')

classSon(Father, Mother):

print("I am son")

x=Son()

x.funcA()

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Multiple Inheritance with Diamond Structure

To solve this python computes mro, method resolution order for a class. This can be found by __mro__. This gives a list of parent classes linearized. So python checks for next in line based on the __mro__.

super follows the mro as well. It does not call the parent of a class. It calls next in line based mro.

The algorithm used for computing the mro is C3 Linearization Algorithm. More details on the algorithm in mro