Lesson 4 of 7 · Classes and Objects · 3 min read · Updated
Polymorphism
One call, many kinds of object — and why Python cares what an object can do, not what it is.
Polymorphism means different types answering the same call in their own way. Your loop does not need to know which kind of object it has — only that it can do what is asked.
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r ** 2, 2)
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
for shape in [Circle(1), Rectangle(3, 4), Circle(2)]:
print(type(shape).__name__, shape.area())
Circle 3.14
Rectangle 12
Circle 12.57
Circle and Rectangle share no parent, yet the loop treats them alike because both have an area() method. Python calls this duck typing: if it walks like a duck and quacks like a duck, treat it as a duck.
print(len("hello"), len([1, 2]), len({"a": 1}))
print("ab" * 2, [0] * 3)
5 2 1
abab [0, 0, 0]
You have used polymorphism since the first lessons: len() works on strings, lists and dictionaries, and * means one thing for numbers and another for strings and lists.
Through a shared parent
class Animal:
def speak(self):
raise NotImplementedError("each animal must speak")
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for animal in [Dog(), Cat()]:
print(animal.speak())
Woof
Meow
Note
The parent's speak raising NotImplementedError documents the promise every child must keep. A child that forgets to override it fails loudly the first time it is asked to speak.
A function calls item.area() on everything in a list. What must each item have?
Try this now
- Add a
Triangleclass witharea()and add it to the shapes loop without changing the loop. - Write classes for UPI, Card and Cash payments, each with
pay(amount), and process a list of mixed payments.
Create a free account to save your progress, or sign in.