DEV Community

Tommi k Vincent
Tommi k Vincent

Posted on

Polymorphism in Python

definition : The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes in a program.

import math


class Shape:
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Creating instances of the subclasses
c1 = Circle(50)
rect = Rectangle(50, 40)

# Calling the area() methods
circle_area = c1.area()
rectangle_area = rect.area()

# Printing the results
print("Area of the circle:", circle_area)
print("Area of the rectangle:", rectangle_area)
Enter fullscreen mode Exit fullscreen mode

This code demonstrates a basic example of object-oriented programming (OOP) by implementing a shape hierarchy. The hierarchy consists of a base class called "Shape" and two subclasses: "Circle" and "Rectangle."

The purpose of the "Shape" base class is to provide a blueprint for calculating the areas of various shapes. It declares a method called "area" without any implementation details. This method acts as a placeholder that will be overridden by the subclasses.

The "Circle" subclass represents a circle and extends the "Shape" class. It has a constructor that accepts the radius as a parameter. Within the class, the "area" method is overridden to calculate the area of a circle using the provided radius. The formula used is math.pi * radius ** 2, where math.pi represents the mathematical constant π.

The "Rectangle" subclass also extends the "Shape" class and takes the length and width as parameters in its constructor. Similarly, it overrides the "area" method inherited from the base class to compute the area of a rectangle using the given length and width. The formula used is simply the product of the length and width.

In the main part of the code, instances of the "Circle" and "Rectangle" classes are created. The circle is initialized with a radius of 50, while the rectangle has a length of 50 and a width of 40. The "area" method is called on each instance, resulting in the respective areas being calculated.

Overall, this code demonstrates the principles of inheritance and polymorphism in OOP. It allows for the creation of different shapes with their specific area calculation formulas while utilizing a common interface defined by the base class.

Top comments (0)