Introduction

Greetings! In today's lesson, we'll unravel the concept of polymorphism in Python's Object-Oriented Programming (OOP). Grasping polymorphism enables us to use a single entity (a method, class, or interface) to represent different types in various scenarios. Let's proceed.

Polymorphism: A Powerful OOP Principle

Polymorphism, a pillar of OOP, allows one object to embody multiple forms. Visualize a button in software; depending on its type (for instance, a submit button or a radio button), the action resulting from pressing it varies. This dynamic encapsulates the spirit of polymorphism!

Seeing Polymorphism in Action

Let's observe polymorphism in action within a simple application involving shapes. The base Shape class has an area method, which calculates the area for shapes. This method is uniquely implemented in the subclasses Rectangle and Circle.

class Shape:
    def area(self):
        pass

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

    def area(self):  # calculate rectangle area
        return self.length * self.width

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

    def area(self):  # calculate circle area
        return 3.14 * self.radius * self.radius

rectangle = Rectangle(2, 3)
print(rectangle.area()) # Prints: 6

circle = Circle(5)
print(circle.area()) # Prints: 78.5

Here, polymorphism shines as the area function takes on multiple forms and behaves differently depending on whether it's part of a Rectangle or a Circle.

When and Why to Use Polymorphism

Polymorphism is indispensable when dealing with inheritance, as a single action can exhibit different behaviors for different object types, streamlining the code while enhancing readability and maintainability.

Polymorphism with Python: Variations and Implementation

Python supports various types of polymorphism. Dynamic polymorphism occurs during runtime and leverages method overriding within the base class. On the flip side, static polymorphism operates during compile time.

Below are illustrative examples of both types.

class Shape:
    def area(self, length=None, width=None, radius=None):
        if radius:  # If the radius is provided, calculate the circle area
            return 3.14 * radius * radius
        elif length and width:  # if length and width are provided, calculate the rectangle area
            return length * width
        else:
            return "Invalid parameters"

shape = Shape()
print(shape.area(length=5, width=2))   # Rectangle area
print(shape.area(radius=3))           # Circle area
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal