Inheritance in Python

Inheritance in Python, Object-Oriented Programming, Types of Inheritance, Single Inheritance, Multiple Inheritance, Multilevel inheritance, Hierarchical inheritance, and Hybrid inheritance.

Inheritance in Python

Inheritance is an important principle of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and methods defined in the parent class.

The parent class is the class being inherited from, also called ‘base’ class.

The child class is the class that inherits from another class, also called ‘derived’ class.

Single Inheritance:

Example:

class Calculator:

def add(self, num1, num2):
return (num1+num2)

def sub(self, num1, num2):
return (num1-num2)

def mul(self, num1, num2):
return (num1*num2)

#child class Mathoperations inherits the base class Calculator

class Mathoperations(Calculator):

def div(self, x, y):
return(x/y)

obj = Mathoperations()

print(obj.add(10, 20))
print(obj.sub(10, 20))
print(obj.mul(10, 20))
print (obj.div(20, 10))

Python Multi-Level inheritance:

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no limit on the number of levels.

class Class1:

def add(self, num1, num2):
return (num1+num2)

def sub(self, num1, num2):
return (num1-num2)

#child class

class Class2(Class1):

def mul(self, num1, num2):
return (num1*num2)

# sub-child class

class Class3(Class2):

def div(self, x, y):
return(x/y)

obj = Class3()

print(obj.add(10, 20))
print(obj.sub(10, 20))
print(obj.mul(10, 20))
print (obj.div(20, 10))

Different forms of Inheritance:

1. Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. We saw an example above.

2. Multiple inheritance: When a child class inherits from multiple parent classes, it is called multiple inheritance.
Unlike Java and like C++, Python supports multiple inheritance. We specify all parent classes as a comma-separated list in the bracket.

3. Multilevel inheritance: When we have a child and grandchild relationship.

4. Hierarchical inheritance More than one derived classes are created from a single base.

5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance.


Python Tutorial
Python Video
Follow me on social media: