Polymorphism
Polymorphism means "many forms". In programming, it's the ability to use the same operation or method name on different types of objects, with each one responding in its own way. It lets you write one piece of code that works with many kinds of data.
You already use polymorphism
Built-in functions and operators behave differently depending on what you give them:
print(len("Nairobi")) # characters in a string
print(len([10, 20, 30])) # items in a list
print(len({"a": 1, "b": 2})) # keys in a dictionary
print(2 + 3) # adds numbers
print("Ku" + "za") # joins strings
print([1, 2] + [3]) # joins lists
One name, len or +, many forms. Your own classes can join in, too.
Polymorphism with methods
If different classes provide a method with the same name, code can call that method without caring which class it's dealing with.
class MPesaPayment:
def __init__(self, phone):
self.phone = phone
def pay(self, amount):
return f"Sent KES {amount} via M-Pesa from {self.phone}"
class CardPayment:
def __init__(self, last_digits):
self.last_digits = last_digits
def pay(self, amount):
return f"Charged KES {amount} to card ending {self.last_digits}"
class CashPayment:
def pay(self, amount):
return f"Received KES {amount} in cash"
def checkout(method, amount):
print(method.pay(amount)) # works for ANY object with a pay() method
for method in [MPesaPayment("0712 345 678"), CardPayment("4242"), CashPayment()]:
checkout(method, 1250)
checkout() never checks the type. Adding a new payment method later, such as bank transfer, needs a new class with a pay() method and no change to checkout() at all. That's the real power of polymorphism: code that is open to new types without being rewritten.
checkout() runs whichever pay() belongs to the object it receives.Duck typing
The payment classes above don't share a parent class. Python doesn't need them to: if an object has the method you call, it works. This is called duck typing, from the saying "if it walks like a duck and quacks like a duck, it's a duck".
class Duck:
def speak(self):
return "Quack!"
class Robot:
def speak(self):
return "Beep boop."
class Rock:
pass
for thing in [Duck(), Robot(), Rock()]:
if hasattr(thing, "speak"):
print(thing.speak())
else:
print(type(thing).__name__, "cannot speak")
Polymorphism through inheritance
With inheritance, child classes override a parent method to give their own version. Any code written for the parent automatically works with the children.
class Notification:
def __init__(self, recipient):
self.recipient = recipient
def send(self, message):
return f"To {self.recipient}: {message}"
class SMS(Notification):
def send(self, message):
return f"SMS {super().send(message[:20])}" # SMS keeps it short
class Email(Notification):
def send(self, message):
return f"EMAIL {super().send(message)}"
alerts = [SMS("0722 000 111"), Email("amina@example.com")]
for alert in alerts:
print(alert.send("Your exam results are now available online"))
Abstract base classes
Sometimes you want to guarantee that every child class provides certain methods. The abc module lets you define an abstract base class: a parent that can't be instantiated and that forces children to implement marked methods.
import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
"""Every shape must say how to calculate its area."""
def describe(self):
return f"{type(self).__name__} with area {self.area()}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return round(math.pi * self.radius ** 2, 2)
for shape in [Rectangle(4, 5), Circle(2)]:
print(shape.describe())
try:
Shape()
except TypeError as error:
print(error)
If someone writes a Triangle(Shape) class and forgets area(), Python refuses to create triangles with a similar error, catching the mistake early. (The exact wording of this message varies slightly between Python versions.)
Writing long if type(obj) == MPesaPayment: ... elif type(obj) == CardPayment: ... chains defeats the purpose of polymorphism. Every new type means editing that chain. Give each class the method and simply call it. If you really need a type check, prefer isinstance(), which also accepts subclasses.
For polymorphism to work, the methods must have the same name and compatible parameters. If CardPayment.pay() needed an extra required argument, checkout() would crash with a TypeError for card payments only.
Key points
- Polymorphism lets one interface (a function, operator or method name) work with many types.
- Duck typing: if an object has the method you need, Python lets you use it.
- Overriding methods in subclasses gives each class its own behaviour.
- Abstract base classes (
ABC,@abstractmethod) force subclasses to implement required methods. - Operators can be polymorphic too, using dunder methods.
Tip: use the ← and → keys to move between pages.
