Class Inheritance Advanced

In Python a class can inherit one or more classes.

Inheriting multiple classes

Let's look at the following example:

Output:

Explanation:

  • At line 9 class C inherits two classes - A and B.
  • Because of that class C has 3 members functions - printA, printB and printC.

Multilevel Inheritance

A class can inherit a class that inherits other class. A long chain can be formed.

Each child in the chain inherits functions and members from the ones before it (it's parents grandparents etc...).

Here's an example:

Output:

Explanation:

  • There is an inheritance chain: A is inherited by B. B is inherited by C. C is inherited by D.
  • At line 5 class B inherits class A.
  • At line 9 class C inherits class B. Class C inherits the members from B and A. So class C has functions - getA, getB and getC.
  • At line 13 class D inherits class C. Class D is at the bottom of the inherit chain. So it inherits members from A, B and C. Class D has functions getA, getB, getC and getD.