Python Polymorphism
Polymorphism — "many forms" — is the OOP pillar that allows the same interface (function name, operator, or method call) to work correctly across different types. Python's polymorphism is particularly elegant because of duck typing: if it walks like a duck and quacks like a duck, it's a duck. This chapter covers all four forms of Python polymorphism: duck typing, method overriding, operator overloading, and abstract base classes — with responsive diagrams and real-world patterns from professional code.
What is Polymorphism?
The word polymorphism comes from Greek — "poly" (many) + "morphe" (form). In
programming it means: the same interface can work with objects of different types. You write
one piece of code that calls shape.area(), and it works correctly whether
shape is a Circle, Rectangle, or Triangle — without changing the calling
code.
v1 + v2 calls __add__.
TypeError if not.
Duck Typing — Python's Structural Polymorphism
Python's most distinctive form of polymorphism. It doesn't care about an object's type or class — only whether it has the method or attribute you're trying to call. The name comes from the phrase: "If it walks like a duck and quacks like a duck, then it must be a duck."
# Duck typing — no common base class needed!
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Robot:
def speak(self):
return "Beep boop!"
# Same function works with ANY object that has speak()
def make_noise(entity):
print(entity.speak()) # Python doesn't check the type!
for thing in [Dog(), Cat(), Robot()]:
make_noise(thing)
# Woof! Meow! Beep boop!
# Real-world duck typing — file-like objects
import io
def write_header(file_obj):
"""Works with any file-like object (file, StringIO, BytesIO)."""
file_obj.write("=== REPORT ===\n") # needs .write() — that's all!
# Works with a real file
with open("report.txt", "w") as f:
write_header(f)
# Also works with StringIO (in-memory file)
buf = io.StringIO()
write_header(buf)
print(buf.getvalue()) # === REPORT ===
# Check duck-type compatibility safely
def safe_speak(obj):
if hasattr(obj, "speak") and callable(obj.speak):
return obj.speak()
return f"(no speak method on {type(obj).__name__})"
StringIO wherever a file is expected, use a custom list-like object with for loops, or pass any "callable" as a callback — the flexibility that makes
Python so productive.
Method Overriding — Inheritance-Based Polymorphism
When multiple child classes override the same parent method, Python selects the correct
implementation at runtime based on the object's actual type. The calling code stays unchanged
— the same for shape in shapes: shape.area() loop calls each class's
unique implementation.
import math
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement area()")
def describe(self):
return f"{type(self).__name__}: area = {self.area():.2f}"
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return math.pi * self.r ** 2
class Rectangle(Shape):
def __init__(self, w, h): self.w = w; self.h = h
def area(self): return self.w * self.h
class Triangle(Shape):
def __init__(self, b, h): self.b = b; self.h = h
def area(self): return 0.5 * self.b * self.h
# Polymorphic loop — one function, many types
shapes = [Circle(5), Rectangle(4,6), Triangle(3,8)]
for shape in shapes:
print(shape.describe())
# Circle: area = 78.54
# Rectangle: area = 24.00
# Triangle: area = 12.00
# Total area — polymorphic sum
total = sum(s.area() for s in shapes)
print(f"Total: {total:.2f}") # Total: 114.54
Operator Overloading
Python lets you redefine what standard operators (+,
-, *, ==, <, etc.) mean for your custom
classes by implementing dunder methods. This is operator overloading — the same operator
symbol works differently for different types.
class Money:
"""Represents a monetary amount with currency."""
def __init__(self, amount, currency="INR"):
self.amount = amount
self.currency = currency
def __add__(self, other): # m1 + m2
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
def __sub__(self, other): # m1 - m2
if self.currency != other.currency:
raise ValueError("Cannot subtract different currencies")
return Money(self.amount - other.amount, self.currency)
def __mul__(self, factor): # m * 3
return Money(self.amount * factor, self.currency)
def __eq__(self, other): # m1 == m2
return self.amount == other.amount and self.currency == other.currency
def __lt__(self, other): # m1 < m2
return self.amount < other.amount
def __str__(self):
return f"{self.currency} {self.amount:,.2f}"
def __repr__(self):
return f"Money({self.amount!r}, {self.currency!r})"
# ── Using natural operators ───────────────────────────
price = Money(1000)
tax = Money(180)
total = price + tax
doubled = price * 2
print(total) # INR 1,180.00
print(doubled) # INR 2,000.00
print(price < total) # True
print(price == Money(1000)) # True
# Sort a list of Money objects
wallet = [Money(500), Money(200), Money(800)]
print(sorted(wallet)) # [INR 200, INR 500, INR 800]
Abstract Base Classes (ABC) — Enforced Contracts
While duck typing is flexible, sometimes you need to enforce that every
subclass implements specific methods. Python's abc module provides ABC and @abstractmethod. If a concrete
subclass doesn't implement all abstract methods, Python raises a TypeError
at instantiation time.
from abc import ABC, abstractmethod
# Abstract base class — defines the interface contract
class PaymentProcessor(ABC):
"""Abstract contract for all payment processors."""
@abstractmethod
def process_payment(self, amount: float) -> bool:
"""Process a payment of the given amount."""
@abstractmethod
def refund(self, transaction_id: str) -> bool:
"""Refund a transaction."""
def get_name(self): # concrete method — shared by all
return type(self).__name__
# ✅ Concrete implementation 1
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"[CreditCard] Charging ₹{amount}")
return True
def refund(self, transaction_id):
print(f"[CreditCard] Refunding {transaction_id}")
return True
# ✅ Concrete implementation 2
class UPIProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"[UPI] Sending ₹{amount} via UPI")
return True
def refund(self, transaction_id):
print(f"[UPI] Reversing UPI {transaction_id}")
return True
# ❌ Incomplete implementation → TypeError at instantiation
class BadProcessor(PaymentProcessor):
def process_payment(self, amount): pass
# Missing refund() !
# BadProcessor() → TypeError: Can't instantiate abstract class BadProcessor
# Polymorphic payment processing
def checkout(processor: PaymentProcessor, amount: float):
print(f"Using {processor.get_name()}")
return processor.process_payment(amount)
for p in [CreditCardProcessor(), UPIProcessor()]:
checkout(p, 1000)
# Using CreditCardProcessor → [CreditCard] Charging ₹1000
# Using UPIProcessor → [UPI] Sending ₹1000 via UPI
Built-in Python Polymorphism
Python's built-in functions and operations are already polymorphic — they work correctly across many types automatically. Understanding this helps you see why polymorphism is so pervasive in Python:
# len() is polymorphic — works on many types
print(len("Python")) # 6 — string length
print(len([1,2,3])) # 3 — list length
print(len({"a":1})) # 1 — dict length
print(len((1,2,3,4))) # 4 — tuple length
# + operator is polymorphic
print(1 + 2) # 3 — int addition
print(1.5 + 2.5) # 4.0 — float addition
print("a" + "b") # "ab" — string concatenation
print([1] + [2,3]) # [1,2,3] — list concatenation
# print() is polymorphic — calls __str__ on any object
print(42) # 42
print("hello") # hello
print([1,2,3]) # [1, 2, 3]
# for loop is polymorphic — works on any iterable
for x in "hello": print(x, end="") # h e l l o
for x in [1,2,3]: print(x, end="") # 1 2 3
for k in {"a":1}: print(k, end="") # a
# max()/min()/sum() — polymorphic across any iterable
print(max(3, 7, 1)) # 7 — positional
print(max([3,7,1])) # 7 — from list
print(max("apple")) # 'p' — max char by ASCII
Real-World Polymorphism Patterns
Polymorphism is the basis of open/closed principle — code that is open for extension (add new types) but closed for modification (don't change existing code). Here are two professional patterns:
# ── Pattern 1: Strategy Pattern via polymorphism ──────
class Sorter:
def sort(self, data): raise NotImplementedError
class BubbleSort(Sorter):
def sort(self, data):
print("Bubble sorting...")
return sorted(data)
class QuickSort(Sorter):
def sort(self, data):
print("Quick sorting...")
return sorted(data)
def process_data(data, sorter: Sorter):
return sorter.sort(data) # polymorphic — doesn't care which sorter
nums = [5, 2, 8, 1]
print(process_data(nums, BubbleSort())) # swap strategy at runtime
print(process_data(nums, QuickSort()))
# ── Pattern 2: Notification system ───────────────────
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message: str): pass
class EmailNotifier(Notifier):
def send(self, message):
print(f"📧 Email: {message}")
class SMSNotifier(Notifier):
def send(self, message):
print(f"📱 SMS: {message}")
class PushNotifier(Notifier):
def send(self, message):
print(f"🔔 Push: {message}")
def notify_all(notifiers, message):
for n in notifiers:
n.send(message) # polymorphic — same call, different channel
notify_all(
[EmailNotifier(), SMSNotifier(), PushNotifier()],
"Your order has shipped!"
)
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all polymorphism examples from this chapter directly in your browser with these free Python environments.
- Polymorphism means "many forms" — the same interface works correctly with objects of different types, making code flexible and extensible.
- Duck typing: Python doesn't check object types — it checks whether the object has the needed method/attribute. If it does, it works. This is Python's most common and flexible polymorphism.
- Method overriding: child classes redefine inherited methods. Python selects the correct version at runtime based on the object's actual type. The calling code never changes.
- Operator overloading: implement dunder methods (
__add__,__eq__,__lt__, etc.) to give custom objects natural operator behaviour. - Abstract Base Classes (from
abcmodule):@abstractmethodforces every concrete subclass to implement specified methods — raisesTypeErrorif not. - Python's built-in functions (
len(),+,print(),for) are already polymorphic — they call dunder methods under the hood. - Polymorphism implements the Open/Closed Principle: add new types (open for extension) without changing existing code (closed for modification).
- Use
hasattr(obj, "method")andcallable(obj.method)for safe duck-type checking when needed.
Duck typing is Python's form of structural polymorphism — named after the phrase "if it walks like a duck and quacks like a duck, it's a duck." Python doesn't check what type an object is; it only checks whether the object has the method or attribute being called.
It's polymorphism without inheritance: a Dog, Cat, and Robot class — none inheriting from a common base — can all be used
polymorphically as long as they each have a speak() method. The
calling code works the same for all three.
Operator overloading means redefining what standard operators (+, -, *, ==, etc.) do for your custom
class by implementing dunder methods.
The + operator calls __add__. Common dunder methods for operators:
__add__→ +,__sub__→ -,__mul__→ *__eq__→ ==,__lt__→ <,__le__→ <=__len__→ len(),__str__→ str()/print()
An abstract method is a method decorated with @abstractmethod in a class that inherits from ABC. It declares an interface that must be implemented by any
concrete (non-abstract) subclass.
If a subclass fails to implement all abstract methods, Python raises a TypeError when you try to instantiate it: TypeError: Can't instantiate abstract class X with abstract method y.
This enforces the interface contract at runtime.
Duck typing is informal and flexible — Python checks at runtime whether the object has the needed attribute, without any class hierarchy requirement. Objects of completely unrelated classes can be used polymorphically.
Abstract Base Classes are formal and enforced — they define a required interface and raise errors at instantiation if a subclass doesn't implement it. They require inheritance and provide a clear contract that's verified at class-definition time.
Use duck typing for flexibility; use ABCs when you need to guarantee an interface is implemented correctly — especially for public APIs and libraries.
The Open/Closed Principle states that software should be open for extension but closed for modification.
Polymorphism enables this perfectly: a function like notify_all(notifiers, message) calls n.send(message) for each notifier. To add a new notification channel
(WhatsApp, Slack), you just create a new class implementing send()
— you never touch the notify_all function. The existing code is
closed for modification; the system is open for extension via new classes.
ABC and @abstractmethod?== operator for a
custom class?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.