Characteristics of Object Oriented programming in Python Part-3

In part-2 of this segment, we discussed Encapsulation. In this post, we’ll discuss Inheritance in detail and its implementation in Python.

Inheritance is the process by which a class can be derived from a base class with all features of a base class and some of its own. This increases code reusability.

Inheritance is a powerful feature in object-oriented programming. It refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.

Python Inheritance Syntax

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

Example of Inheritance in Python

A polygon is a closed figure with 3 or more sides. Let us make a class with name Polygon.

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])

This class has data attributes to store the number of sides, n and magnitude of each side as a list, sides.

Method inputSides() takes in magnitude of each side and similarly, dispSides() will display these properly.

A triangle is a polygon with 3 sides. So, we can created a class called Triangle which inherits from Polygon. This makes all the attributes available in class Polygon readily available in Triangle. We don’t need to define them again (code re-usability). Triangle is defined as follows.

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)

However, theTriangleclass has a new method tofindArea() and print the area of the triangle. Here is a sample 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

As we can see that, even though we did not define methods like inputSides() or dispSides() for class Triangle, we were able to use them.

Leave a Reply