Sub topic 7
Polymorphism: one call, many behaviors
This chapter assumes you can define classes, write instance methods that use self, override a method in a subclass, and use isinstance(). Earlier chapters covered those topics.
What polymorphism means here
Polymorphism means one call works on objects of different classes, and each object responds in its own way. In Python the call site names a method, such as speak(). Python looks that method up on the object's own class, so the object decides which code runs.
Overriding makes this possible. A parent class defines a method, and each subclass replaces it with its own version. Code that calls the method does not need to know which subclass it received.
A worked example
The loop below calls speak() on every item in a list. It contains no type checks.
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 # inherits Animal.speak unchanged
def chorus(animals):
for animal in animals:
print(animal.speak())
chorus([Dog("Rex"), Cat("Tom"), Fish("Bubbles")])This prints:
Rex barks
Tom meows
Bubbles makes a soundchorus() has one line that calls speak(). Three classes give three results. Fish does not override the method, so lookup finds Animal.speak.
Adding a new subclass without changing callers
Polymorphism pays off when requirements grow. To add a Bird, you write the class and nothing else. chorus() stays as it is.
Compare that with code that checks types:
def chorus_branching(animals):
for animal in animals:
if isinstance(animal, Dog):
print(f"{animal.name} barks")
elif isinstance(animal, Cat):
print(f"{animal.name} meows")
else:
print(f"{animal.name} makes a sound")Every new animal forces an edit here, and it is easy to forget one. The knowledge of how each animal speaks belongs in the animal's class, not in the caller.
Common errors
- Branching on type in the caller. A chain of
isinstance()checks that picks behavior defeats the purpose. Useisinstance()to validate input, not to dispatch behavior. - Different signatures across subclasses. If
Dog.speak()takes no arguments butCat.speak(loud)requires one,chorus()fails on theCat. Keep the parameters compatible so any subclass can be called the same way. - Different return types. If
Dog.speak()returns a string andCat.speak()prints and returnsNone, the caller cannot treat them alike. - Calling a method the parent never defines. If
chorus()callsanimal.fetch(), only subclasses with that method work. Define the method on the parent, or the call fails withAttributeError.
Polymorphism without inheritance
Python does not require a shared parent. Any object with a suitable speak() method works in chorus():
class Robot:
def speak(self):
return "Beep"
class Parrot:
def speak(self):
return "Hello"
for thing in [Robot(), Parrot()]:
print(thing.speak())This style is called duck typing: if an object has the method you call, it is usable. Inheritance still helps. A shared parent documents the expected interface and supplies default behavior, and the next chapter shows how to enforce that interface.
Exercise
Given class Shape: def describe(self): return "a shape" and class Circle(Shape): def describe(self): return "a circle", what does [s.describe() for s in [Shape(), Circle()]] return, and why does the list comprehension need no isinstance() check?
Show answer
It returns ['a shape', 'a circle']. Python looks up describe on each object's own class, so Shape() runs Shape.describe and Circle() runs the overriding Circle.describe. The caller only needs the method name, so no type check is needed.
Exercise
A subclass defines def speak(self, volume): while the parent defines def speak(self):. A loop calls animal.speak() on a mixed list. What happens when it reaches the subclass instance, and how do you fix it?
Show answer
It raises TypeError because the required volume argument is missing. Fix it by giving volume a default, such as def speak(self, volume=1):, so the subclass accepts the same calls as the parent.