Inheritance is one of the powerful features of Python since it is an Object Oriented Programming Language.

What is Inheritance in Python?

Inheritance in python is a way through which we can use the property of one class into another class. This ensures the reusability of code and hence reduces the complexity of the program.

The class which inherits other class is called Base Class and the class which has been inherited is known as derived class.

Python Inheritance Block Diagram

Block Diagram of Inheritance in Python

Python Inheritance Syntax

It is important to note that we should only inherit from another class if there is a ‘IS A‘ relationship.

For example, Dog is an Animal.

Let’s see this in action in with python program.

Recommended: Class and objects in Python.

Example 1: Inheritance in Python

To inherit or extend a class we need to declare the derived class name with the base class name inside the parenthesis.

Output

Explanation

We have first created class ‘Animal’ then inherited it into ‘Dog’ class. Using Super() method we have called Animal class __init__() method from Dog class __init() method.

Super() method returns the reference of Base class, hence allowing us to use base class into any derived class.

After which we have created Dog class object and called all the methods both of Animal and Dog class. As you can see, that without any error we are able to call Animal class method’s eat() using Dog class object, which proves that we have successfully inherited Animal class into Dog class i.e implemented inheritance.

Let’s see one more example of inheritance.

Example 2: Inheritance in Python

Output

Hope now you will feel a little bit confident in writing inheritance related programs in python. If you have any doubts then comment below.

Leave a Reply

Close Menu