Sub topic 7
Polymorphism: one call, many behaviors
This chapter assumes you can define classes, write methods that use self, override a method in a subclass, call super(), and use isinstance(). It builds on those to show how overriding lets one piece of code work with many kinds of objects.
What polymorphism means
Polymorphism means "many forms". In Python, it means you can call the same method name on different objects and each object runs its own version of that method. The caller does not need to know which kind of object it holds.
Inheritance makes this easy to set up. A parent class defines a method name. Each subclass overrides it with its own behavior. Code written against the parent works with every subclass.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
class Fish(Animal):
pass
def chorus(animals):
for animal in animals:
print(animal.speak())
chorus([Dog("Rex"), Cat("Tom"), Fish("Nemo"), Animal("Generic")])Output:
Rex barks
Tom meows
Nemo makes a sound
Generic makes a soundThe function chorus contains one call, animal.speak(). That call produces four different results. Fish does not override speak(), so attribute lookup finds the version in Animal. A subclass can take part in polymorphism without writing any code of its own.
How the right method gets chosen
Python picks the method when the call runs, not when the code is written. This is called dynamic dispatch. For animal.speak(), Python looks at the actual class of the object in animal, searches that class and then its parents in order, and runs the first speak it finds.
The diagram below shows the sequence for one call.
Because the choice happens at call time, you can add a new subclass later and chorus will handle it without any change.
Polymorphism without a common parent
Python does not require a shared base class for polymorphism. If an object has the method you call, the call works. This style is often called duck typing: "if it walks like a duck and quacks like a duck, treat it as a duck".
class Dog:
def speak(self):
return "Woof"
class Robot:
def speak(self):
return "Beep"
for thing in (Dog(), Robot()):
print(thing.speak())Dog and Robot are unrelated classes. The loop works because both have speak().
Inheritance still has value. It documents the intended relationship, shares code, and lets you use isinstance() checks and abstract base classes (covered in the next chapter). Duck typing is lighter and more flexible. Inheritance is more explicit. Many Python designs use both.
Polymorphism with shared behavior
Polymorphism becomes more useful when the parent method does common work and calls overridable methods for the parts that differ. The parent controls the overall steps. The subclasses fill in the details. This is sometimes called the template method pattern.
class Report:
def __init__(self, title, rows):
self.title = title
self.rows = rows
def render(self):
lines = [self.header()]
lines.extend(self.format_row(row) for row in self.rows)
return "\n".join(lines)
def header(self):
return self.title
def format_row(self, row):
return str(row)
class CsvReport(Report):
def header(self):
return "# " + self.title
def format_row(self, row):
return ",".join(str(value) for value in row)
class BulletReport(Report):
def format_row(self, row):
return "- " + " ".join(str(value) for value in row)
rows = [(1, "apple"), (2, "pear")]
for report in (Report("Fruit", rows), CsvReport("Fruit", rows), BulletReport("Fruit", rows)):
print(report.render())
print()Output:
Fruit
(1, 'apple')
(2, 'pear')
# Fruit
1,apple
2,pear
Fruit
- 1 apple
- 2 pearNeither subclass defines render(). It runs from Report, but inside it, self.header() and self.format_row(row) are looked up on the actual object. So render() uses each subclass's overrides. The name self is the key here: it always refers to the real instance, not to the class where the running method was written.
Choosing behavior with a dictionary or a method
Beginners often reach for if chains that check the type of an object. This works but goes against polymorphism.
class Circle:
def __init__(self, r):
self.r = r
class Rect:
def __init__(self, w, h):
self.w = w
self.h = h
def area_checked(shape):
if isinstance(shape, Circle):
return 3.14159 * shape.r ** 2
elif isinstance(shape, Rect):
return shape.w * shape.h
raise TypeError("unknown shape")Every new shape forces an edit to area_checked. The polymorphic version moves each calculation into its class.
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
class Rect:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def total_area(shapes):
return sum(shape.area() for shape in shapes)
print(total_area([Circle(1), Rect(2, 3)]))Adding Triangle now means writing one new class. total_area stays unchanged.
The table compares the two approaches.
| Approach | Adding a new type | Adding a new operation | Where the logic lives |
|---|---|---|---|
| `isinstance()` chain | Edit every function that has a chain | Write one new function | In the function |
| Polymorphic methods | Write one new class | Edit every class | In each class |
Neither approach wins every time. If your types change often and operations are stable, methods are better. If operations change often and types are stable, a function with a chain (or match) can be simpler.
Polymorphism and built-in operations
Python's built-in functions and operators are polymorphic through special methods. len(x) calls x.__len__(). print(x) calls x.__str__(). a + b calls a.__add__(b). When you override these in a subclass, built-in behavior changes with it.
class Money:
def __init__(self, cents):
self.cents = cents
def __str__(self):
return f"${self.cents / 100:.2f}"
def __add__(self, other):
return Money(self.cents + other.cents)
class Euro(Money):
def __str__(self):
return f"€{self.cents / 100:.2f}"
print(Money(250))
print(Euro(250))
print(Money(100) + Money(50))Output:
$2.50
€2.50
$1.50Note that Euro(100) + Euro(50) would return a Money, not a Euro, because __add__ builds Money(...) explicitly. Polymorphism only helps where the code calls methods on self or on the object. A hard-coded class name inside a method opts out of it. To keep the subclass type, use type(self)(...):
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other):
return type(self)(self.cents + other.cents)
class Euro(Money):
pass
print(type(Euro(100) + Euro(50)).__name__)This prints Euro.
Common errors
- Different signatures. If
Dog.speak(self)takes no arguments butCat.speak(self, loud)requires one,chorusfails with aTypeErrorfor cats. Keep the same parameters across overrides, or make extra ones optional. The chapter on substitutability returns to this. - Different return types. If
Dog.speak()returns a string andCat.speak()prints and returnsNone, callers that use the result break. Treat the return type as part of the method's contract. - Forgetting that Python checks only names. A misspelled override such as
speekis a new method. Calls tospeak()still reach the parent version, and nothing warns you. Abstract base classes catch this for required methods. - Using
type(x) is SomeClassfor dispatch. An exact type comparison rejects subclasses. Useisinstance()when you must check, and prefer a method when you can. - Hard-coding a class name. As shown with
Money, writingMoney(...)inside a method means subclasses cannot keep their own type.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speek(self): # typo: this is a new method, not an override
return "Woof"
print(Dog().speak())This prints ..., because Dog never overrode speak.
Summary of the working model
- A method call looks up the name on the object's actual class, then its parents in order.
- The first match runs, and
selfinside it is the real object. - So one call site can run different code for different objects.
- Parent methods that call
self.other_method()hand control to subclass overrides. - A hard-coded class name or an
isinstance()chain bypasses that and reduces flexibility.
Exercise
A Shape base class has describe(), which returns f"{self.name()} with area {self.area():.1f}". Shape.name() returns "shape", and Shape.area() returns 0. Write Square(side) and Circle(radius) subclasses that override name() and area() but not describe(). What does describe() return for Square(2), and why does the subclass version of name() run even though describe() is written in Shape?
Show answer
Square(2).describe() returns "square with area 4.0" if Square.name() returns "square" and Square.area() returns self.side ** 2. describe() is looked up on Square, not found there, and found on Shape. Inside it, self is the Square instance, so self.name() and self.area() are looked up starting at Square, and the overrides run. The class where the calling method is written does not affect which overrides are chosen.
Exercise
This function breaks when a new Triangle class is added: def perimeter(s): if isinstance(s, Square): return 4 * s.side elif isinstance(s, Circle): return 2 * 3.14159 * s.radius. How would you redesign it so adding Triangle needs no change to perimeter?
Show answer
Add a perimeter() method to each shape class (Square, Circle, Triangle), each with the same signature and returning a number. Then perimeter(s) becomes return s.perimeter(), or the function is dropped and callers use the method directly. A new class only has to supply its own perimeter() method.