Skip to content

Module 11 · Object-Oriented Programming — topic 20 of 25

Polymorphism

One interface, many forms: polymorphism through inheritance and overriding, duck typing, operator and built-in function polymorphism, and writing code that works with any type supporting an interface.

Beginner 10 min read·Lesson 177 of 306 in Python Programming

Learning objectives

  • Write functions that work with many types through a shared interface
  • Explain duck typing
  • Recognise polymorphism in built-in functions and operators

Definition

Polymorphism means that the same operation or method call works on objects of different types, with each type supplying its own behaviour. In Python it comes from overriding and from duck typing: if an object has the needed method, it can be used.

Introduction

len works on strings, lists and dictionaries. + adds numbers and joins strings. A checkout function can charge a card, a UPI ID or a wallet. That is polymorphism: one call, many behaviours.

Why it matters

Polymorphism lets you add new types without changing the code that uses them. Instead of a growing if/elif chain on types, each object knows how to do its own job.

Detailed explanation

Inheritance-based polymorphism: subclasses override a method from a common parent, and calling code uses the parent's interface.

Duck typing: Python doesn't require a common parent. 'If it walks like a duck and quacks like a duck, it's a duck' — any object with a speak() method can be passed to code that calls speak().

Built-in polymorphism: len(), iter(), str() and the operators call special methods (__len__, __iter__, __str__, __add__), so they work on any type that defines them.

Code that checks types with long if isinstance(...) chains usually misses a chance for polymorphism: move the varying behaviour into the classes.

When a shared interface must be guaranteed, abstract base classes or typing.Protocol make the expectation explicit.

Syntax

Python
def checkout(method, amount):
return method.pay(amount) # works for any object with pay()
checkout(Upi("asha@bank"), 250)
checkout(Card("4242"), 250)
  • Same call, different behaviour per type.
  • Rely on methods, not on type checks.
  • Duck typing needs no common parent.

Code examples

Built-in polymorphism

Python
for item in ["hello", [1, 2, 3], {"a": 1, "b": 2}, range(10)]:
print(type(item).__name__, len(item))
print(2 + 3, "ab" + "cd", [1] + [2])
Output
str 5
list 3
dict 2
range 10
5 abcd [1, 2]

Duck typing

Python
class Duck:
def speak(self):
return "Quack"
class Robot:
def speak(self):
return "Beep"
def make_it_speak(thing):
return thing.speak()
print([make_it_speak(x) for x in [Duck(), Robot()]])
Output
['Quack', 'Beep']

More examples

Payment methods behind one interface

Python
class Payment:
def pay(self, amount):
raise NotImplementedError
class Upi(Payment):
def __init__(self, vpa):
self.vpa = vpa
def pay(self, amount):
return f"UPI {self.vpa}: Rs {amount}"
class Card(Payment):
FEE = 0.02
def __init__(self, last4):
self.last4 = last4
def pay(self, amount):
return f"Card *{self.last4}: Rs {amount * (1 + self.FEE):.2f} (incl. fee)"
class Wallet(Payment):
def __init__(self, balance):
self.balance = balance
def pay(self, amount):
if amount > self.balance:
return f"Wallet: declined, balance Rs {self.balance}"
self.balance -= amount
return f"Wallet: Rs {amount}, left Rs {self.balance}"
def checkout(method, amount):
print(method.pay(amount))
for m in [Upi("asha@bank"), Card("4242"), Wallet(300)]:
checkout(m, 250)
checkout(Wallet(100), 250)
Output
UPI asha@bank: Rs 250
Card *4242: Rs 255.00 (incl. fee)
Wallet: Rs 250, left Rs 50
Wallet: declined, balance Rs 100

Step-by-step explanation

  • checkout knows nothing about UPI, cards or wallets; it only calls pay.
  • Each class implements pay with its own rules: a card adds a fee, a wallet checks its balance.
  • Adding a new method such as NetBanking means writing one class — checkout doesn't change.

Expected output

Running “Payment methods behind one interface” prints exactly:

TextOutput
UPI asha@bank: Rs 250
Card *4242: Rs 255.00 (incl. fee)
Wallet: Rs 250, left Rs 50
Wallet: declined, balance Rs 100

Practical applications

  • File-like objects: anything with read() can be passed to json.load.
  • Payment gateways, storage backends and notification channels behind one interface.

Best practices

  • Design around what objects can do, not what they are.
  • Keep method names and signatures consistent across implementations.
  • Use ABCs or Protocols to document required methods.

Common mistakes

Type-checking instead of polymorphism

Avoid

if isinstance(m, Upi): ...
elif isinstance(m, Card): ...

Prefer

m.pay(amount)

Every new type would require editing the if/elif chain.

Important notes

  • Python has no method overloading by parameter type; default arguments and functools.singledispatch cover those cases.

Key takeaways

  • Polymorphism: one call, behaviour depends on the object.
  • Comes from overriding and duck typing.
  • Replaces type-checking chains with methods on the classes.

Try it yourself

  1. 1
    Add a NetBanking payment class and run it through checkout unchanged.
  2. 2
    Write a total_area(shapes) function that works with any object having an area() method.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module