After this lesson you can write one piece of code that works with many kinds of object, as long as each one offers the method you call.
Same call, different behaviour
The word polymorphism is long, but the idea is short: "many forms". You send the same message, such as area(), to different objects, and each one answers in the way that suits it.
You have already seen it in the built-in functions. len() works on strings, lists and dictionaries, and each type counts in its own way:
print(len("library"))
print(len([10, 20, 30]))
print(len({"a": 1, "b": 2}))7
3
2Polymorphism with inheritance
When classes share a parent, each subclass overrides a method, and code that loops over them does not need to know which is which. Consider shapes in a drawing program:
import math
class Shape:
def area(self):
raise NotImplementedError("subclasses must provide area()")
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
shapes = [Square(3), Circle(1), Square(2)]
for shape in shapes:
print(type(shape).__name__, round(shape.area(), 2))Square 9
Circle 3.14
Square 4The loop calls shape.area() without any if asking which kind of shape it has. If you later add a Triangle class, the loop works without a change. That is the payoff: new behaviour added by writing a new class, not by editing old code.
The raise NotImplementedError in the parent is a signal to whoever writes a subclass: "you must supply this method". If they forget, calling it gives a clear message:
Shape().area()NotImplementedError: subclasses must provide area()Duck typing
In many languages the shapes above would all need a shared parent. Python does not insist. It follows the saying "if it walks like a duck and quacks like a duck, it is a duck". In other words, Python does not care what class an object is. It only tries the method you called, and it works if the method is there.
class Invoice:
def __init__(self, amount):
self.amount = amount
def total(self):
return self.amount
class Basket:
def __init__(self, prices):
self.prices = prices
def total(self):
return sum(self.prices)
def print_total(thing):
print("Total:", thing.total())
print_total(Invoice(40))
print_total(Basket([5, 10, 2.5]))Total: 40
Total: 17.5Invoice and Basket have no common parent. print_total is happy with both because both have total(). The same idea is why you can pass a file, a list of lines, or a string buffer to code that only loops over lines.
If an object lacks the method, the call fails at that point:
print_total("just a string")AttributeError: 'str' object has no attribute 'total'Trying instead of checking
Beginners often protect against wrong types with lots of isinstance checks. In Python it is usually neater to just try and handle the failure if it matters:
def safe_total(thing):
try:
return thing.total()
except AttributeError:
return "cannot total this"
print(safe_total(Basket([1, 2])))
print(safe_total(42))3
cannot total thisThere are places where isinstance is right, for example when two different types really need different handling. Just do not put it everywhere out of habit.
Operators are polymorphic too
Even + is polymorphic. It adds numbers, joins strings and joins lists:
print(2 + 3)
print("ab" + "cd")
print([1, 2] + [3])5
abcd
[1, 2, 3]The next-but-one lesson shows how to make + work on your own classes.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Checking the type before every call. Long
if isinstance(...)chains defeat the point of polymorphism. - Forgetting to override. A subclass that forgets a method silently inherits the parent's version, which may be a placeholder.
- Giving the same method name different meanings. If
total()returns a number on one class and a string on another, callers break. - Catching too much. A bare
except:around a method call hides real bugs inside the method. Catch the specific error. - Believing duck typing means no errors. Errors are found when the code runs, so test the paths you care about.
Exercise
Write classes Cat and Dog, each with a method speak() returning "Meow" and "Woof". Write a class Robot with a speak() that returns "Beep" and no parent class. Put one of each in a list and print the result of speak() for every item.
Show one possible answer
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
class Robot:
def speak(self):
return "Beep"
for creature in [Cat(), Dog(), Robot()]:
print(creature.speak())Meow
Woof
BeepKey points
- Polymorphism means different kinds of object respond to the same method call in their own way.
- With inheritance, each subclass overrides a method, and the calling code does not need to know which subclass it has.
- Duck typing means Python cares about what an object can do, not what class it is.
- Built-in functions such as len() work on many types because those types support the same operation.
- Prefer trying the operation, and handling the error, over checking types with isinstance everywhere.