Types of inheritance Python

Inheritance is the capacity of a particular class to obtain or inherit properties from another class and then use them when required. Inheritance has the following characteristics:

  • It is an excellent representation of relationships in the real world.
  • It allows code reuse. It doesn't require us to create the same code repeatedly and again. It also allows us to add options to an existing class without having to modify the existing code.
  • It is a transitive nature, meaning that if B is inherited from another class A, all the subclasses belonging to B will inherit directly from class A.

Example:

Output:

Jackie False
johnny True

Types of Inheritance in Python

The types of inheritance depend on the number of children and parents involved. There are four kinds of inheritance available in Python:

Single Inheritance Single inheritance allows a derivate class to inherit properties of one parent class, and this allows code reuse and the introduction of additional features in existing code.

Types of inheritance Python

Example:

Output:

This function is defined inside the parent class.
This function is defined inside the child class.

Multiple Inheritance If a class is able to be created from multiple base classes, this kind of Inheritance is known as multiple Inheritance. When there is multiple Inheritance, each of the attributes that are present in the classes of the base has been passed on to the class that is derived from it.

Types of inheritance Python

Example:

Output:

Father name is : Rajesh
Mother name is : Shreya

Multilevel inheritance, the features that are part of the original class, as well as the class that is derived from it, are passed on to the new class. It is similar to a relationship involving grandparents and children.

Types of inheritance Python

Example:

Output:

John Jr Jr
Grandfather name is : John Jr Jr
Father name is : John Jr
Son name is : John

Hierarchical Inheritance If multiple derived classes are created from the same base, this kind of Inheritance is known as hierarchical inheritance. In this instance, we have two base classes as a parent (base) class as well as two children (derived) classes.

Types of inheritance Python

Example:

Output:

This function is defined inside the parent class.
This function is defined inside the child 1.
This function is defined inside the parent class.
This function is defined inside the child 2.





Latest Courses