Python – Inheritance

Inheritance enables us to define a class that takes all the functionality from a parent class and allows us to add more. In this tutorial, you will learn to use inheritance in Python.

Inheritance in Python

In object-oriented programming, inheritance is a powerful feature.

It refers to creating a new class with minimal or no changes to an existing one. The new class is known as the derived (or child) class, whereas the one it inherits from is known as the base (or parent) class.


Python Inheritance Syntax

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class

Derived classes inherit characteristics from the base class and can be extended with new ones. As a result, code can be reused.


Example of Inheritance in Python

To demonstrate the use of inheritance, let us take an example.

A polygon is a closed figure with 3 or more sides. Say, we have a class called Polygon defined as follows.

class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])The number of sides n and the magnitude of each side are stored as a list called sides in this class's data attributes. Ad

The magnitude of each side is taken into account by the inputSides() method, and the side lengths are displayed by dispSides().

A triangle is a three-sided polygon. As a result, we may create a Triangle class that inherits from Polygon. The Triangle class now has access to all of the Polygon class's characteristics.

They don't need to be defined again (code reusability). The following is a definition of a triangle.

The number of sides n and the magnitude of each side are stored as a list called sides in this class’s data attributes. Ad

The magnitude of each side is taken into account by the inputSides() method, and the side lengths are displayed by dispSides().

A triangle is a three-sided polygon. As a result, we may create a Triangle class that inherits from Polygon. The Triangle class now has access to all of the Polygon class’s characteristics.

They don’t need to be defined again (code reusability). The following is a definition of a triangle.

class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self,3)

    def findArea(self):
        a, b, c = self.sides
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
        print('The area of the triangle is %0.2f' %area)

The class Triangle, on the other hand, includes a new method findArea() that finds and prints the triangle’s area. Here’s an example of a test run.

>>> t = Triangle()

>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> t.findArea()
The area of the triangle is 6.00

We can see that we were able to utilize methods like inputSides() and dispSides() even though we didn’t declare them individually for class Triangle.

If an attribute can’t be discovered in the class, the search moves on to the base class. If the base class is derived from additional classes, the process repeats recursively.

Types of Inheritance in Python

The number of child and parent classes involved determines the types of inheritance. In Python, there are four types of inheritance:

 

Single Inheritance: Single inheritance allows a derived class to inherit properties from a single parent class, allowing for code reuse and new capabilities to be added to existing code.
 

Example:

# Python program to demonstrate
# single inheritance
 
 
# Base class
class Parent:
     def func1(self):
          print("This function is in parent class.")
 
# Derived class
class Child(Parent):
     def func2(self):
          print("This function is in child class.")
 
# Driver's code
object = Child()
object.func1()
object.func2()

Output:

This function is in parent class.
This function is in child class.

Multiple Inheritance: Many inheritance is a type of inheritance in which a class can be derived from multiple base classes. In multiple inheritance, the derived class inherits all of the features of the base classes.
 

Example:

# Python program to demonstrate
# multiple inheritance
 
 
# Base class1
class Mother:
    mothername = ""
    def mother(self):
        print(self.mothername)
 
# Base class2
class Father:
    fathername = ""
    def father(self):
        print(self.fathername)
 
# Derived class
class Son(Mother, Father):
    def parents(self):
        print("Father :", self.fathername)
        print("Mother :", self.mothername)
 
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

Output:

Father : RAM
Mother : SITA

Multilevel Inheritance:Features from the base class and the derived class are passed down to the new derived class in multilevel inheritance. This is comparable to the relationship between a child and his grandfather.
 

Example:

# Python program to demonstrate
# multilevel inheritance
 
# Base class
class Grandfather:
 
    def __init__(self, grandfathername):
        self.grandfathername = grandfathername
 
# Intermediate class
class Father(Grandfather):
    def __init__(self, fathername, grandfathername):
        self.fathername = fathername
 
        # invoking constructor of Grandfather class
        Grandfather.__init__(self, grandfathername)
 
# Derived class
class Son(Father):
    def __init__(self,sonname, fathername, grandfathername):
        self.sonname = sonname
 
        # invoking constructor of Father class
        Father.__init__(self, fathername, grandfathername)
 
    def print_name(self):
        print('Grandfather name :', self.grandfathername)
        print("Father name :", self.fathername)
        print("Son name :", self.sonname)
 
#  Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()

Output:

Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

Hierarchical Inheritance: Hierarchical inheritance refers to the process of creating multiple derived classes from a single base class. We have a parent (base) class and two child (derived) classes in this program.
 

Example:

# Python program to demonstrate
# Hierarchical inheritance
 
 
# Base class
class Parent:
      def func1(self):
          print("This function is in parent class.")
 
# Derived class1
class Child1(Parent):
      def func2(self):
          print("This function is in child 1.")
 
# Derivied class2
class Child2(Parent):
      def func3(self):
          print("This function is in child 2.")
  
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Output:

This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.


Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
 

Example:

# Python program to demonstrate
# hybrid inheritance
 
 
class School:
     def func1(self):
         print("This function is in school.")
  
class Student1(School):
     def func2(self):
         print("This function is in student 1. ")
  
class Student2(School):
     def func3(self):
         print("This function is in student 2.")
  
class Student3(Student1, School):
     def func4(self):
         print("This function is in student 3.")
  
# Driver's code
object = Student3()
object.func1()
object.func2()

Output:

This function is in school.
This function is in student 1.

Leave a Comment

Your email address will not be published.