Instagram
youtube
Facebook
Twitter

Inheritance

  • Inheritance in python is a way of assigning properties of one class to another.
  • Inheritance works on the concept of Parent and child class. Where in child class inherits the properties of the Parent class.
  • Inheritance allows us to share the methods across classes. Which increases the reusability of the code.

Python Inheritance Example

 

class Calculator:
    def sum1(a, b):
        return a + b
    
    def subs(a, b):
        return a - b

    def multi(a, b):
        return a*b

    def divi(a, b):
        return a/b

class ComplexCalculator(Calculator):
    def avg(sumo, n):
        return sumo/n

a = int(input())
b = int(input())

sumo = ComplexCalculator.sum(a, b)
output = ComplexCalculator.avg(sumo, 2)
print(output) 

 

Here in the example above, there are two classes. One Calculator is for the parent class and second ComplexCalculator which is the child class. And as you can see the child class inherits the proporties of parent class calculator.

At the end we have created and object which calls sum method directly using ComplexCalculator class as this class inherits the Calculator class. That is the why we were able to access this.


Types of Inheritance in Python

  1. Single Level Inheritance
  2. Multi Level Inheritance
  3. Multiple Inheritance
  4. Herarichal Inheritance
  5. Hybrid Inheritance

1. Single Level Inheritance

In this type of inheritance there is one parent component which is inherited by one child component. Hence it is known as single level inheritance

 

class Parent:
    pass

class Child(Parent):
    pass

 

2Multi Level Inheritance

In multilevel inheritance one parent class is inherited by one child class. Then the same child class is inherited by another child class.

class Parent:
    pass

class Child1(Parent):
    pass

class Child2(Child1):
    pass

 

3. Multiple Inheritance

When a child class inherits more than one parent classes it is known as Multiple Inheritacne.

class Parent:
    pass

class Parent2:
    pass

class Child(Parent, Parent2):
    pass

 

4. Herarichal Inheritance

When One parent class is inherited between multiple child classes it is known as herarichal inheritance.

 

class Parent:
    pass

class Child1(Parent):
    pass

class Child2(Parent):
    pass

 

5. Hybrid Inheritance

Inheritance which is the mixture of one or more types of inheritance is known as Hybrid Inheritance.