Thuta Learning
Python
IntermediateProgrammingBeginner

Polymorphism (Enhanced)

PythonLesson 2325 min

What you'll walk away with

  • Replace an if/elif isinstance() chain with a single method call
  • Explain duck typing and why it works without inheritance
  • Give examples of polymorphic built-ins such as len() and +
  • Document a required interface with abc.ABC plus @abstractmethod or with typing.Protocol

Explain it simply

Explain it simply

Press the Power button on a remote: a TV turns on as a TV, an air conditioner turns on as an air conditioner. There is one button and one command, yet each device responds in its own way. That is polymorphism, which literally means "many forms".

In code, calling shape.area() makes a Circle compute πr² and a Rectangle compute width × height. The caller does not need to know which kind of shape it holds; it only needs to know that the object has an area() method.

Problem → Why → Solution

The problem: every new type means another elif

Without polymorphism, a function that totals areas often checks types like the one below. On the day a new Triangle class is added, forgetting to update total_area() means triangles are silently skipped and the total is wrong. If the project has ten functions like this, every new shape means editing ten places.

areas_by_type.py
def total_area(shapes):
    total = 0
    for s in shapes:
        if isinstance(s, Circle):
            total += 3.14159 * s.radius ** 2
        elif isinstance(s, Rectangle):
            total += s.width * s.height
        # Triangle was added later... and silently ignored here
    return total

Why is this design fragile?

The knowledge of how to compute each shape's area lives outside the shape classes, so whoever writes a new class cannot know this function exists. Move each formula into an area() method on its own class, and total_area() only has to call s.area(); it never changes again when a shape is added.

Core concept: one call, many implementations

The heart of polymorphism is that the caller performs one operation and the object itself decides which code runs. When you call shape.area(), Python looks up area on the shape's class at runtime, so a Circle in the list gets Circle.area() and a Rectangle gets Rectangle.area(). Python offers polymorphism in three main forms.

1. Inheritance plus overriding

A parent class such as Shape defines the method name area(), and each child class overrides it. A parent method like describe() that calls self.area() then gets each child's own version.

2. Duck typing

The name comes from "if it walks like a duck and quacks like a duck, it is a duck". Python does not check an object's type, only whether the method exists. The Plot class in the example does not inherit from Shape, yet total_area() accepts it because it has area(). Passing an object without the method fails only at the moment of the call, with AttributeError.

3. Built-in and operator polymorphism

len() works on strings, lists and dicts, and + adds numbers but concatenates strings and lists. Behind the scenes, len(x) calls x.__len__() and a + b calls a.__add__(b); the magic methods lesson shows how your own classes plug into this.

Duck typing is flexible, but nothing in the code states which methods are required. The abc module's ABC with @abstractmethod makes Python raise TypeError as soon as you try to create an object of a subclass that skipped a required method. typing.Protocol instead describes "any object with area() -> float" for type checkers, without inheritance. Either way, the key move is that callers invoke one common operation instead of branching on concrete types, so adding a type never forces edits to existing code.

Mental model: the object decides
  1. Caller calls thing.area()
  2. Python finds area on thing's class
  3. That class's own code runs
  4. The caller never inspects the type

Adding a type means writing one new class with the method; callers stay untouched.

General pattern

python
class KindA:
    def operation(self):
        return "A's way"

class KindB:
    def operation(self):
        return "B's way"

def use_all(items):
    for item in items:
        item.operation()          # no isinstance() checks

The classes only need the same method name and parameters; a shared parent is optional. The caller just calls the method and never branches on the type.

Example: shapes and a total area

Circle and Rectangle inherit from Shape and override area(). Plot, a piece of land, has nothing to do with Shape, but total_area() accepts it because it has area(). The last two lines show built-in polymorphism.

shapes.py
import math


class Shape:
    def area(self):
        raise NotImplementedError("subclasses must implement area()")

    def describe(self):
        return f"{type(self).__name__} with area {self.area():.2f}"


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

    def area(self):
        return math.pi * self.radius ** 2


class Rectangle(Shape):
    def __init__(self, width, height):
        self.width, self.height = width, height

    def area(self):
        return self.width * self.height


class Plot:                      # NOT a Shape, but it has area()
    def __init__(self, acres):
        self.acres = acres

    def area(self):
        return self.acres * 4046.86


def total_area(things):
    return sum(thing.area() for thing in things)   # no type checks


shapes = [Circle(1), Rectangle(3, 4)]
for shape in shapes:
    print(shape.describe())

print(round(total_area(shapes + [Plot(0.5)]), 2))

# Built-in polymorphism: one operation, many types
print(len("Sai"), len([1, 2, 3, 4]), len({"a": 1, "b": 2}))
print(2 + 3, "py" + "thon", [1] + [2])

Code breakdown

  1. Line 6raise NotImplementedError("subclasses must implement area()")

    Shape itself has no formula. If a child forgets to override area(), calling it fails with a clear message.

  2. Line 9return f"{type(self).__name__} with area {self.area():.2f}"

    describe() is written once in Shape, yet self.area() calls each child's own version. :.2f formats the result to two decimal places.

  3. Line 28class Plot: # NOT a Shape, but it has area()

    Duck typing: Plot does not inherit from Shape. total_area() only calls area(), so Plot is accepted.

  4. Line 37return sum(thing.area() for thing in things) # no type checks

    Not a single isinstance(). π + 12 + 0.5 × 4046.86 gives 2038.57, and adding a new shape never requires touching this line.

  5. Lines 47-48print(2 + 3, "py" + "thon", [1] + [2])

    The same operator adds (5), joins strings (python) or joins lists ([1, 2]) depending on the types involved.

You should see
Circle with area 3.14
Rectangle with area 12.00
2038.57
3 4 2
5 python [1, 2]

Stating the interface with ABC and Protocol

NotImplementedError only surfaces when the method is called. An ABC catches the problem earlier, at object creation. Square below forgot area(), so Square(2) raises TypeError immediately.

abstract_shape.py
from abc import ABC, abstractmethod

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

class Square(Shape):
    def __init__(self, side):
        self.side = side
    # forgot to write area()

try:
    Square(2)
except TypeError as e:
    print(e)

typing.Protocol needs no inheritance at all. Field never mentions HasArea, but because it has area() -> float, a type checker such as mypy accepts it in report(). At runtime the Protocol adds no checks.

protocol_shape.py
from typing import Protocol

class HasArea(Protocol):
    def area(self) -> float: ...

class Field:                      # never mentions HasArea
    def area(self) -> float:
        return 120.0

def report(item: HasArea) -> str:
    return f"area = {item.area()}"

print(report(Field()))

In real projects

Where this shows up in real projects

Python's "file-like object" is the classic duck-typing example. json.dump(data, f) never checks whether f is a disk file, an io.StringIO or a network wrapper; it just calls f.write(). That is why tests can pass a StringIO instead of a real file and inspect the output in memory.

In a payment system, CardPayment, WalletPayment and BankTransfer all have a charge(amount) method, and the checkout code simply calls payment.charge(total). Adding a new payment method means writing one new class. The same pattern appears in notifications, export formats such as CSV, JSON and PDF, and storage backends such as local disk or S3. Libraries like the Django ORM and Python's logging handlers rely on it too: give your class the expected methods and the framework can use it.

Common mistakes

Common mistakes

1. Overriding, then checking the type anyway

If the classes already have area() but the caller still writes if type(s) == Circle:, the benefit of polymorphism is gone. type() == is even worse because it also rejects subclasses. Move the type-specific work into the method.

2. Giving the shared method different signatures

If Circle.area(self) exists but Rectangle.area(self, unit) takes an extra argument, total_area() calling thing.area() fails on the Rectangle with TypeError: "missing 1 required positional argument: 'unit'". Polymorphic methods must share their parameters; give any extra one a default value.

3. Returning different kinds of value

If one class returns a number from area() and another returns a string such as "12 m²", sum() raises TypeError. A shared method name is not enough; the meaning and type of the result must match too.

Best practices

Best practices

  • Keep polymorphic methods identical in name, parameters and return type, and document once what the method must return.
  • Choose an ABC when you own the classes and want missing methods caught early; choose a Protocol when third-party classes should fit too.
  • When you see the same type-based if/elif in more than two places, it is time to move it into a method on the classes.
  • Trust duck typing, but at a library's public boundary give a clear error message when an object lacks the needed method.

Mini challenge

Mini challenge: notification channels

Write three sender classes that each have send(message), and a notify_all() function that calls them all without checking types.

  • EmailSender(address) and SmsSender(phone) each return a string
  • SmsSender sends only the first 17 characters plus "..." when the message is longer than 20
  • LogSender has no shared parent and works purely through duck typing
  • notify_all(senders, message) contains no isinstance()
notify.py
class EmailSender:
    def __init__(self, address):
        self.address = address

    def send(self, message):
        # TODO: return "email to <address>: <message>"
        pass


class SmsSender:
    # TODO: __init__(self, phone) and send(self, message)
    # TODO: shorten messages longer than 20 characters
    pass


# TODO: LogSender with send(self, message) -> "log: <message>"


def notify_all(senders, message):
    # TODO: print what every sender returns, without isinstance()
    pass

Expected: Output of notify_all(channels, "Your order has shipped"): email to aye@example.com: Your order has shipped sms to 09-555: Your order has sh... log: Your order has shipped

Show hint

message[:17] + "..." keeps the first 17 characters and appends "...". notify_all() only needs a for loop with print(sender.send(message)).

Show solution
notify.py
class EmailSender:
    def __init__(self, address):
        self.address = address

    def send(self, message):
        return f"email to {self.address}: {message}"


class SmsSender:
    def __init__(self, phone):
        self.phone = phone

    def send(self, message):
        short = message if len(message) <= 20 else message[:17] + "..."
        return f"sms to {self.phone}: {short}"


class LogSender:
    def send(self, message):
        return f"log: {message}"


def notify_all(senders, message):
    for sender in senders:
        print(sender.send(message))


channels = [EmailSender("aye@example.com"), SmsSender("09-555"), LogSender()]
notify_all(channels, "Your order has shipped")

Quick quiz 1 / 3

Given class A: def go(self): return "A" and class B: def go(self): return "B" with no common parent, what does print([x.go() for x in [A(), B(), A()]]) show?

Quick quiz 2 / 3

Shape(ABC) has an @abstractmethod area(). What happens on Blob() for class Blob(Shape) that never defines area()?

Quick quiz 3 / 3

An export function has a growing if fmt == "csv": ... elif fmt == "json": ... chain. What is the polymorphic fix?

What to remember

  • Polymorphism lets the caller perform one operation while the object decides which code runs.
  • Python offers overriding, duck typing, and polymorphic built-ins such as len() and +.
  • Replace if/elif isinstance() chains with a method on each class.
  • State the required interface with ABC plus @abstractmethod, or with typing.Protocol.

Python Documentation — Classes — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Polymorphism (Enhanced) | Thuta Learning