Python Polymorphism

← Back to Home

Understanding Python Polymorphism: A Beginner-Friendly Guide



What is Polymorphism in Python?

Polymorphism literally means "many forms". In programming, it allows different objects to respond to the same method call in their own way. This makes your code flexible and reusable.

For example, consider the method area() , a Circle, Square, and Triangle all have it, but each calculates area differently. This is polymorphism in action.

Python implements polymorphism as a core principle of Object-Oriented Programming (OOP), letting us write cleaner, adaptable code.



Why Use Polymorphism?

  • Code Reusability: Write functions or methods that work on multiple object types.
  • Flexibility: Add new classes without modifying existing code.
  • Simplicity: Reduce complexity by handling objects in a general way.
  • DRY Principle: Avoid repeating code across multiple classes.


Types of Polymorphism in Python

  1. Duck Typing
  2. Method Overriding
  3. Operator Overloading


1. 🦆 Duck Typing


"If it walks like a duck and quacks like a duck, it is considered a duck."

Python focuses on the behavior of objects rather than their specific type. If an object has the required method or attribute, it can be used regardless of its class.

class Parrot:
    def speak(self):
        return "Squawk!"

class Dog:
    def speak(self):
        return "Bark!"

def make_sound(animal):
    print(animal.speak())

make_sound(Parrot())  # Squawk!
make_sound(Dog())     # Bark!

Even though Parrot and Dog are unrelated classes, they both work with make_sound() because they implement the speak() method.



2. Method Overriding

Method overriding occurs when a child class provides its own version of a method defined in the parent class. Python will use the child class method instead of the parent class method when called on a child object.

class Appliance:
    def turn_on(self):
        print("Turning on appliance...")

class Fan(Appliance):
    def turn_on(self):
        print("Turning on fan...")

a = Appliance()
a.turn_on()  # Turning on appliance...

f = Fan()
f.turn_on()  # Turning on fan...

Here, the same method turn_on() behaves differently depending on whether it’s called on Appliance or Fan.



3. Operator Overloading

Python allows operators like +, *, and others to behave differently depending on the objects involved.

class Box:
    def __init__(self, volume):
        self.volume = volume

    def __add__(self, other):
        return Box(self.volume + other.volume)

box1 = Box(20)
box2 = Box(35)
total = box1 + box2
print(total.volume)  # 55

Here, the + operator adds the volume attributes rather than combining the objects themselves. This is operator overloading.



Advanced Polymorphism Topics

1. Polymorphism with Abstract Classes

Python’s abc module allows creation of abstract classes with abstract methods. Child classes must implement these methods.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

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

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

c = Circle(5)
print(c.area())  # 78.5

2. Polymorphism in Collections

Polymorphism allows handling objects of different classes in the same collection seamlessly.

shapes = [Circle(3), Circle(5)]

for shape in shapes:
    print(shape.area())

This works because all objects share the same method area().

3. Polymorphism with Interfaces

Although Python does not have formal interfaces, abstract base classes can act as interfaces, allowing polymorphic behavior across multiple classes.



Key Takeaways

  • Polymorphism allows writing general-purpose, reusable code.
  • It simplifies handling of diverse object types without knowing their exact class.
  • Python supports polymorphism via duck typing, inheritance, abstract classes, and operator overloading.
  • It is crucial for writing scalable, maintainable, and DRY code.


FAQs About Polymorphism

Q1. What is the main advantage of polymorphism?

It allows code reuse and flexibility by letting one function or method work with different object types.

Q2. Is polymorphism only for classes?

No, Python supports polymorphism for functions, operators, and even collections as long as objects share behavior.

Q3. How is method overriding different from duck typing?

Method overriding requires inheritance and occurs at the class level. Duck typing works purely based on the presence of a method or attribute, regardless of inheritance.

Q4. Can operator overloading be applied to all operators?

Most Python operators can be overloaded using special methods like __add__, __sub__, __mul__, etc.



Call to Action

Polymorphism is a powerful tool for any Python programmer. Start practicing by creating your own classes and experimenting with duck typing, method overriding, and operator overloading. Apply these concepts in small projects to see how much cleaner and more maintainable your code can become.

For further learning, explore our post on Python Classes and Objects to strengthen your foundation.