Python

Polymorphism is a core concept in Object-Oriented Programming (OOP) that comes from the Greek words Poly (many) and Morph (forms). In Python, it refers to the ability of different classes to be treated as instances of the same general class through a single interface.

1. Theoretical Overview

The "Many Forms" Concept

Polymorphism allows a single function, method, or operator to behave differently depending on the object it is acting upon.

  • Example: The len() function is polymorphic. It can take a string and return the number of characters, or it can take a list and return the number of elements. The "interface" is the same (len()), but the internal logic changes based on the data type.

Types of Polymorphism in Python

  1. Duck Typing: "If it walks like a duck and quacks like a duck, it’s a duck." Python doesn't care about the object's type, only whether it has the required methods.

  2. Method Overriding: A child class provides a specific implementation of a method that is already defined in its parent class.

  3. Operator Overloading: Using the same operator (like +) for different purposes (e.g., adding numbers vs. concatenating strings).

2. Code Implementation

A. Polymorphism with Function (Duck Typing)

We can create a function that takes any object and calls a method on it, regardless of the object's class.

Python
class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

# This function is polymorphic
def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!

B. Polymorphism with Class Methods (Overriding)

This is common when multiple child classes inherit from a parent but need to perform the same action in different ways.

Python
class Shape:
    def area(self):
        pass

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

    def area(self):
        return 3.14 * (self.radius ** 2)

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

shapes = [Circle(5), Square(4)]

for shape in shapes:
    print(f"Area: {shape.area()}")

3. Comparison Table

FeatureDescription
InterfaceThe method name remains the same (e.g., .speak() or .area()).
FlexibilityAllows you to write code that can handle new class types without modification.
RelationshipOften works hand-in-hand with Inheritance (Overriding).

4. Why use Polymorphism?

  • Simplicity: You don't need to check the type of an object (if isinstance...) before calling a method.

  • Scalability: You can add a new class (e.g., class Triangle) to your project, and any polymorphic functions you already wrote will work with it automatically.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now