Python OOP
Polymorphism
Complete lesson for Polymorphism using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Polymorphism
Section: Python OOP. One interface, many behaviours — duck typing, overriding, operator overloading, and functions that accept many types.
What is polymorphism?
- Polymorphism means “many forms”: the same operation name behaves differently on different types.
- In Python it appears as duck typing, method overriding, and operator overloading.
- Callers write one piece of code; each object supplies its own behaviour.
class Dog:
def speak(self) -> str:
return "Woof"
class Cat:
def speak(self) -> str:
return "Meow"
try:
for animal in (Dog(), Cat()):
print(animal.speak())
except Exception as e:
print("Error:", e) Kinds of polymorphism (practical view)
- Python is dynamically typed, so polymorphism is often implicit — no cast required.
| Kind | Idea | Python example |
|---|---|---|
| Subtype / runtime | Override methods | Dog.speak vs Cat.speak |
| Duck typing | Same method names, no shared base | file-like .read() |
| Operator | Same operator, different types | 3+4, "a"+"b", list + |
| Function | One function, many types | len(x) for str/list/dict |
Overriding for polymorphic loops
- A shared method name lets you iterate heterogeneous objects.
- Optional shared ABC documents the contract; duck typing also works.
class Shape:
def area(self) -> float:
raise NotImplementedError
class Circle(Shape):
def __init__(self, r: float) -> None:
self.r = r
def area(self) -> float:
return 3.14 * self.r * self.r
class Square(Shape):
def __init__(self, s: float) -> None:
self.s = s
def area(self) -> float:
return self.s * self.s
try:
for shape in (Circle(2), Square(3)):
print(type(shape).__name__, shape.area())
except Exception as e:
print("Error:", e) Duck typing polymorphism
- No common parent required — only the called method must exist.
- Missing methods raise
AttributeErrorat runtime — catch and report clearly.
class PdfReport:
def render(self) -> str:
return "PDF bytes"
class HtmlReport:
def render(self) -> str:
return "<html>...</html>"
def publish(report) -> None:
print(report.render())
try:
publish(PdfReport())
publish(HtmlReport())
publish(object())
except AttributeError as e:
print("Error:", e) Built-in polymorphic functions
len,iter,str,repr,hashdispatch to dunder methods on the object.- Your classes become polymorphic with builtins by implementing those dunders.
class Team:
def __init__(self, members: list[str]) -> None:
self.members = members
def __len__(self) -> int:
return len(self.members)
try:
print(len("abc"), len([1, 2]), len({"a": 1}), len(Team(["A", "B", "C"])))
except Exception as e:
print("Error:", e) Operator polymorphism
+means add for numbers, concat for sequences — decided by operands’ types.- Custom classes overload via
__add__,__eq__, etc. (see Magic Methods topic).
try:
print(10 + 5)
print("Learn" + "Code")
print([1, 2] + [3])
print((1, 2) + (3,))
except TypeError as e:
print("Error:", e) Polymorphism without inheritance
- Pass any callable, any iterable, any context manager — protocols by convention.
- This is idiomatic Python and differs from Java’s “must implement interface” style.
def total(items) -> float:
s = 0.0
for x in items:
s += float(x)
return s
try:
print(total([1, 2, 3]))
print(total((1.5, 2.5)))
print(total({"4", "5"}))
except Exception as e:
print("Error:", e) Advanced — Polymorphism
Single dispatch (ad hoc polymorphism)
functools.singledispatchoverloads a function by the type of the first argument.- Useful when you cannot or should not add methods onto existing types.
from functools import singledispatch
@singledispatch
def describe(obj) -> str:
return f"object:{obj!r}"
@describe.register
def _(obj: int) -> str:
return f"int:{obj}"
@describe.register
def _(obj: list) -> str:
return f"list-len:{len(obj)}"
try:
print(describe(10))
print(describe([1, 2, 3]))
print(describe(3.14))
except Exception as e:
print("Error:", e) Method resolution and polymorphism
- For
obj.method(), Python binds the function found ontype(obj)via MRO. - Parent references are not needed — variables are untyped names holding objects.
Avoid type switches when methods suffice
- Long
if isinstancechains are a smell — prefer polymorphic methods or singledispatch. - Keep isinstance for external/unknown objects or security boundaries.
# Prefer this style over many isinstance branches
class Email:
def send(self) -> None:
print("send email")
class SMS:
def send(self) -> None:
print("send sms")
try:
for msg in (Email(), SMS()):
msg.send()
except Exception as e:
print("Error:", e) Numeric polymorphism and NotImplemented
- If
__add__cannot handle a type, returnNotImplementedso Python tries the reflected__radd__. - Raising
TypeErroryourself is OK for clear demos; production operators often useNotImplemented.
class Money:
def __init__(self, amount: float) -> None:
self.amount = amount
def __add__(self, other):
if isinstance(other, Money):
return Money(self.amount + other.amount)
return NotImplemented
def __repr__(self) -> str:
return f"Money({self.amount})"
try:
print(Money(10) + Money(5))
print(Money(10) + 3)
except TypeError as e:
print("Error:", e) Polymorphism and typing
- Use Protocols or ABCs so type checkers understand polymorphic parameters.
- At runtime, behaviour still follows duck typing unless you enforce checks.
Tricky Interview Points
Q1) What is polymorphism in Python?
Answer The ability to use the same operation or method name with different types providing their own behaviour — via overriding, duck typing, or operators.
Q2) How is polymorphism different from Java’s?
Answer Python relies heavily on duck typing and does not require a shared interface type, though ABCs/Protocols can document contracts.
Q3) Give examples of built-in polymorphism.
Answer len() on str/list/dict; + on int/str/list; iter() on any iterable; open().read() vs StringIO.read().
Q4) What is duck typing?
Answer An object is usable if it implements the needed methods/attributes, regardless of its inheritance tree.
Q5) How do you achieve runtime polymorphism?
Answer Override methods in subclasses (or independent classes with the same API) and call through a common method name.
Q6) What is operator overloading?
Answer Defining dunder methods so operators like +, ==, < work on your types.
Q7) What does singledispatch do?
Answer functools.singledispatch registers multiple implementations of one function selected by the first argument’s type.
Q8) Why return NotImplemented from __add__?
Answer Signals Python to try the other operand’s reflected method instead of immediately failing.
Q9) Is overloading by argument count supported?
Answer Not like Java. Use default args, *args, @singledispatch, or explicit pattern matching.
Q10) Polymorphism vs inheritance?
Answer Inheritance is a reuse/relationship mechanism; polymorphism is about interchangeable behaviour. Inheritance often enables subtype polymorphism but is not required in Python.
Q11) How does len() work on a custom class?
Answer Implement __len__ returning a non-negative integer; len(obj) calls it.
Q12) What error appears when a duck-typed method is missing?
Answer AttributeError. Catch it and print a clear message in demos and user-facing tools.
Simple Programs
Notify via polymorphic send()
class Email:
def send(self, text: str) -> None:
print(f"EMAIL: {text}")
class SMS:
def send(self, text: str) -> None:
print(f"SMS: {text}")
class Push:
def send(self, text: str) -> None:
print(f"PUSH: {text}")
try:
channels = [Email(), SMS(), Push()]
for ch in channels:
ch.send("Exam results published")
except Exception as e:
print("Error:", e) Media players — duck typed play()
class Mp3:
def play(self) -> None:
print("Playing MP3")
class Streaming:
def play(self) -> None:
print("Streaming audio")
def start(player) -> None:
player.play()
try:
start(Mp3())
start(Streaming())
except Exception as e:
print("Error:", e) singledispatch area helper
from functools import singledispatch
import math
@singledispatch
def area(shape) -> float:
raise TypeError(f"unsupported shape {type(shape)!r}")
@area.register
def _(shape: tuple) -> float:
# (width, height) rectangle
w, h = shape
return w * h
@area.register
def _(shape: float) -> float:
# radius as float → circle
return math.pi * shape * shape
try:
print(round(area(2.0), 2))
print(area((3, 4)))
print(area("nope"))
except TypeError as e:
print("Error:", e) Polymorphic len and str
class Deck:
def __init__(self, cards: list[str]) -> None:
self.cards = cards
def __len__(self) -> int:
return len(self.cards)
def __str__(self) -> str:
return f"Deck({len(self)} cards)"
try:
d = Deck(["A", "K", "Q", "J"])
print(len(d))
print(d)
except Exception as e:
print("Error:", e) Safe duck call
def close_quietly(resource) -> None:
try:
resource.close()
except AttributeError as e:
print("Error:", e)
class Handle:
def close(self) -> None:
print("closed")
try:
close_quietly(Handle())
close_quietly(123)
except Exception as e:
print("Error:", e) Problem Solving Tricks
- Design functions around behaviours (
read,send), not concrete class names. - Replace isinstance ladders with methods or singledispatch.
- Implement
__len__/__iter__to plug into polymorphic builtins. - Return
NotImplementedfrom binary dunders for symmetric operators. - Protocols document duck typing for type checkers.
- Prefer small interfaces: one method often beats fat base classes.
+on lists concatenates;+=may mutate — know the difference.- Catch
AttributeError/TypeErrorat API boundaries and print messages. - Demo polymorphism with a for-loop over mixed objects.
- Remember: Python chooses the method from the object’s class, not a declared variable type.
Practice Programs List
- Create Dog/Cat/Cow with
speak(); print all in one loop. - Write
render(doc)that works for Pdf and Html without a shared base. - Implement
__len__and__getitem__on a custom Series class. - Use singledispatch to format int, float, and list differently.
- Show
+polymorphism for int, str, and a custom Money class. - Refactor an isinstance chain into polymorphic methods.
- Call a missing duck method and catch AttributeError; print
e. - Build Notification Email/SMS/Push with identical
sendsignatures. - Make
total(iterable)work for list, tuple, and set of numbers. - Add a Protocol
Playableand type-hint astart(player: Playable)function.