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:
- Multiple Inheritance
- 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:
So just like a child inherits characteristics from both mother and father, in python, we can inherit multiple classes in a single child class.
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:
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
.
Here is a simple example, its just to explain you how this looks in code:
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.
In order to check if Child
class is a child class of Parent
class.
True
Or using the object of the classes,
It’s pretty much the same,
True