TExcelTAD
Home › Python › Python Polymorphism

Python Polymorphism

Polymorphism ("many forms") means that the same operation can work on different types of objects, each doing the right thing for itself. You call shape.area() without caring whether the shape is a circle or a square — each object knows how to compute its own area.

You already use polymorphism all the time with built-ins:

python · try it yourself
print(len("hello"))          # characters in a string
print(len([1, 2, 3]))        # items in a list
print(len({"a": 1, "b": 2})) # keys in a dict

print(1 + 2)                 # addition
print("ab" + "cd")           # concatenation
print([1] + [2])             # list joining
5
3
2
3
abcd
[1, 2]

len() and + are one interface with many implementations.

Polymorphism with class methods

Different classes can provide methods with the same name. Code that uses them only needs to know the name:

python · try it yourself
import math

class Circle:
    def __init__(self, r):
        self.r = r
    def area(self):
        return math.pi * self.r ** 2
    def name(self):
        return "circle"

class Rectangle:
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h
    def name(self):
        return "rectangle"

shapes = [Circle(1), Rectangle(3, 4), Circle(2.5)]
for s in shapes:
    print(f"{s.name():<10} {s.area():8.2f}")

print(f"total area: {sum(s.area() for s in shapes):.2f}")
circle         3.14
rectangle     12.00
circle        19.63
total area: 34.78

Circle and Rectangle share no parent class here, yet the loop treats them uniformly.

Duck typing

Python doesn't check an object's type before calling a method; it just tries. "If it walks like a duck and quacks like a duck, it's a duck." Any object with the right method works:

python · try it yourself
class Robot:
    def speak(self):
        return "Beep boop"

class Parrot:
    def speak(self):
        return "Hello, hello!"

class Rock:
    pass

def make_it_talk(thing):
    if hasattr(thing, "speak"):
        print(thing.speak())
    else:
        print(f"A {type(thing).__name__} can't talk.")

for t in [Robot(), Parrot(), Rock()]:
    make_it_talk(t)
Beep boop
Hello, hello!
A Rock can't talk.

Polymorphism through inheritance

With a shared base class, subclasses override a method and code written against the base works for all of them. The base class can also offer shared behaviour built on top of the overridden method:

python · try it yourself
class Notifier:
    def send(self, message):
        raise NotImplementedError

    def broadcast(self, messages):
        for m in messages:
            print(self.send(m))

class EmailNotifier(Notifier):
    def send(self, message):
        return f"[email] {message}"

class SmsNotifier(Notifier):
    def send(self, message):
        return f"[sms] {message[:10]}"

for n in [EmailNotifier(), SmsNotifier()]:
    n.broadcast(["Server restarted successfully"])
[email] Server restarted successfully
[sms] Server res

Abstract base classes

To force subclasses to implement a method, use the abc module. A class with an unimplemented @abstractmethod can't be instantiated:

python · try it yourself
from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        ...

class Card(Payment):
    def pay(self, amount):
        return f"Paid {amount} by card"

print(Card().pay(25))
try:
    Payment()
except TypeError as err:
    print("TypeError:", str(err).split(" with")[0])
Paid 25 by card
TypeError: Can't instantiate abstract class Payment

Operator polymorphism

Your own classes can support +, ==, len() and more by defining magic methods like __add__ and __len__ — the topic of the Magic Methods lesson.

Form of polymorphism How it looks
Built-in functions len(x), str(x) work on many types
Same-named methods shape.area() on unrelated classes
Duck typing "has a .speak()? then call it"
Overriding subclass replaces a base method
Operator overloading a + b calls a.__add__(b)

Tip: Write functions against behaviour ("needs something with .read()"), not concrete types. Your code becomes reusable with objects you never anticipated.

Test yourself

What is duck typing?

  1. Checking types with isinstance before every call
  2. Using an object based on the methods it has, not its declared type
  3. A way to copy objects
  4. Inheriting from a Duck class

What happens when you try to instantiate a class with an unimplemented @abstractmethod?

  1. It works normally
  2. A TypeError is raised
  3. The method returns None
  4. A warning is printed