Types of Inheritance in Python

In the last tutorial we learned about Inheritance and how a child class can inherit a parent class to utilise its properties and functions.

What if a class want to inherit more than one class? Or it it possible to inherit a class, which already inherits some other class? To answer these questions, lets see the different types of Inheritance.

In Python, there are two types of Inheritance:

  1. Multiple Inheritance
  2. Multilevel Inheritance

Python - Multiple Inheritance

Multiple Inheritance means that you're inheriting the property of multiple classes into one. In case you have two classes, say A and B, and you want to create a new class which inherits the properties of both A and B, then:

class A:
    # variable of class A
    # functions of class A

class B:
    # variable of class A
    # functions of class A

class C(A, B):
    # class C inheriting property of both class A and B
    # add more properties to class C

So just like a child inherits characteristics from both mother and father, in python, we can inherit multiple classes in a single child class.

Multiple Inheritance in Python

As you can see, instead of mentioning one class name in parentheses along with the child class, we have mentioned two class names, separated by comma ,. And just to clear your doubts, yes, you can inherit as many classes you want. Therefore, the syntax should actually be:

class A(A1, A2, A3, ...):
    # class A inheriting the properties of A1, A2, A3, etc.
  	# You can add properties to A class too


Python - Multilevel Inheritance

In multilevel inheritance, we inherit the classes at multiple separate levels. We have three classes A, B and C, where A is the super class, B is its sub(child) class and C is the sub class of B.

Multilevel Inheritance in Python

Here is a simple example, its just to explain you how this looks in code:

class A:
    # properties of class A

class B(A):
    # class B inheriting property of class A
    # more properties of class B

class C(B):
    # class C inheriting property of class B
    # thus, class C also inherits properties of class A
    # more properties of class C

Using issubclass() method

In python, there is a function which helps us to verify whether a particular class is a sub class of another class, that built-in function is issubclass(paramOne, paramTwo), where paramOne and paramTwo can be either class names or class's object name.

class Parent:
  	var1 = 1
  	def func1(self):
  	    # do something

class Child(Parent):
  	var2 = 2
  	def func2(self):
  	    # do something else

In order to check if Child class is a child class of Parent class.

>>> issubclass(Child, Parent)

True

Or using the object of the classes,

Parent p = Parent()
Child c = Child()

It's pretty much the same,

>>> issubclass(c, p)

True