Polymorphism: one call, many shapes
🌍 In real life. The ▶ button means "play" on a music app, a video app and a radio. You press the same button every time, and each one does the right thing for itself: plays a song, starts a film, tunes in a station. You don't need to know how each one works inside.
Polymorphism (Greek for "many shapes") is the same idea in code: different classes have a method with the same name, so one line like shape.area() works on all of them, and each answers in its own way.
The idea in one sentence: if different classes have a method with the same name, one line like shape.area() works on all of them, and each answers its own way.
Its words:
- polymorphism: one call, many shapes of answer
- common interface: the method names every class agrees to have, like
area() - duck typing: Python only checks that the object has the method you call, not which class it came from
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return round(3.14159 * self.radius * self.radius, 2)
shapes = [Square(3), Rectangle(2, 5), Circle(1)]
for s in shapes:
print(type(s).__name__, s.area())Inheritance and polymorphism work well together: the parent can describe what every child must do, and each child decides how. Here a payment app treats every way of paying the same, so adding a new one later doesn't change the checkout code at all:
class Payment:
def __init__(self, amount):
self.amount = amount
def receipt(self):
return self.method() + ": " + str(self.amount) + " taka"
class Cash(Payment):
def method(self):
return "Cash"
class Card(Payment):
def method(self):
return "Card"
class Mobile(Payment):
def method(self):
return "Mobile wallet"
for p in [Cash(200), Card(550), Mobile(75)]:
print(p.receipt())Python doesn't even need the classes to be related. If an object has the method you call, it works. People call this duck typing: "if it walks like a duck and quacks like a duck, treat it as a duck".
class Duck:
def speak(self):
return "Quack"
class Robot:
def speak(self):
return "Beep boop"
for thing in [Duck(), Robot()]:
print(thing.speak())Why it helps. Code that loops over shapes, payments or animals doesn't need an if for each kind. Adding a new kind later means writing one new class; the loop stays exactly as it is.
Mistakes and edge cases.
- A class missing the method. A shape without
area()breaks the loop with an AttributeError on that item. - Different names for the same job.
area()in one class andget_area()in another isn't polymorphism: the shared call fails. - Checking the type instead.
if type(s) == Square: ... elif type(s) == Circle: ...undoes the benefit; let each class answer for itself.
Quiz
What does this print?
class A: def hello(self): return "A" class B: def hello(self): return "B" print([x.hello() for x in [A(), B(), A()]])What does polymorphism let you do?
- Use one line, like s.area(), for objects of different classes
- Make a class with two names
- Run methods faster
What does this print?
class Shape: def describe(self): return "I have " + str(self.sides()) + " sides" class Triangle(Shape): def sides(self): return 3 class Square(Shape): def sides(self): return 4 print(Triangle().describe()) print(Square().describe())What does this print?
class Cow: def sound(self): return "Moo" class Car: def sound(self): return "Vroom" print(" and ".join(x.sound() for x in [Cow(), Car()]))Which line has a mistake?
class Square: def __init__(self, side): self.side = side def area(self): return self.side * self.side class Circle: def __init__(self, radius): self.radius = radius def get_area(self): return 3 * self.radius * self.radius print([s.area() for s in [Square(2), Circle(1)]])
Coding tasks
SquareandRectangleare written for you. Writetotal_area(shapes)that returns the sum of every shape'sarea().Write two classes,
Duck(whosespeak()returns"Quack") andRobot(whosespeak()returns"Beep"), and a functionchorus(things)that returns a list of what each thing says.