Python Inheritance With Example

aimtocode

Inheritance Definition

Inheritance is the advance feature of python in object oriented programming, it allows us to define a class that inherits all the methods and properties from another class.

Inheritance in python is a mechanism in which one object acquires all the properties and behaviors of parent object.

The idea behind inheritance in python is that the user can create new classes that are built upon already existing classes.

When inheriting from an existing class, the users can reuse methods and fields of parent class, and can add new methods and fields also.

Inheritance is also known as parent-child relationship.

Inheritance Syntax:

 class parent:
     statements
                    
 class child(parent):
     statements

Example:



Output:

 This is Parent Class
 This is Child Class

Properties of base class

  • This is the mother class from whose attributes and functions could be inherited.
  • The common attributes of the program are put inside base class.
  • The attributes and functions of the base class could be changed by the derived class.
  • Base class will be more general and can have any number of derived classes.

Properties of derived class

  • This can enhance the data members and functions derived from the base class.
  • Derived class will be more specific.
  • A derived class can have any number of base classes.
  • A derived class can access all the non-private members of its base class.
  • Derived class can inherit either the entire base class or a part of the base class.
  • The derived class can also act as a base class for more level of inheritance.
  • The derived class may inherit from more than one base class.
  • All the base class non-private members and functions could be accessed by derived class object.

Types of Inheritance in Python

In Python, there are four types of Inheritance:

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

Single Inheritance

A class extends another class (only one class).

Syntax:

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

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

Example:



Output:

 This is Parent Class
 This is Chile Class


Multiple Inheritance

In Python, One class extending (Or inherits) more than one base class is called Multiple Inheritance.

Syntax:



Example:



Output:

 This is Parent Class
 This is Parent Class2
 Inherited both Parent and Parent2 class 


Python - Multilevel Inheritance

One class can inherited from a derived class, thereby making this derived class the base classs for the new class is called Multi-level Inheritance.

Syntax:



Example:




Hierarchical Inheritance

One Class is inherited by many sub classes is called Hierarchical Inheritance in python.

Example:



Output:

 This is Parent Class
 Child Class inheriting Parent class
 Child2 Class inheriting Parent class	
aimtocode