Topics

Types of Inheritance

Welcome to another tutorial, here you will learn about the types of Inheritance in Python. In one of the previous tutorials, you were introduced to Inheritance.

If we are faced with a situation where a class wants to inherit more than one class, what will be done? Is it even possible to inherit a class that already inherits another class? The next session will enable us to answer these questions. So sit tight.

There are two types of Inheritance in Python. They are:

  • Multiple Inheritance
  • Multilevel Inheritance

 

Multiple Inheritance

This type of Inheritance is a situation where you are inheriting the property of multiple classes into a single class. For instance, we have two classes, A and B, and we desire to create a new class that inherits the properties of both A and B. check below:

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

This is simply like a child which inherits characteristics from the mother and father; with python, we can inherit multiple classes in a single child class.

 

As you can see, rather than stating just one class name in the parenthesis, along with the child class, we mentioned the two class names, but separated by a comma ','. 

So, you can see that it is possible to inherit as many classes as desired.

The general syntax is:

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

 

Multilevel Inheritance

In this type of Inheritance, you will inherit the classes at multiple separate levels. Suppose, we have three classes A, B, and C; A is the superclass, B is its sub(or child) class and C is the sub-class of B.

 

Check out the example below to better understand this concept.

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 programming, there is a function that can assist in verifying if a particular class is a sub-class of another class, i.e. 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

 

But, to check if the Child class is a child class of Parent class:

>>> issubclass(Child, Parent)

Output:

true

 

Or we can use the object of the classes,

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

It's pretty much the same,

>>> issubclass(c, p)

Output:

True