← Python from Scratch Lesson 70 of 78 · 10 XP

Polymorphism

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Polymorphism means "many forms": different objects respond to the same call in their own way, and the calling code doesn't care who it's dealing with.

animals = [Dog("Sharik"), Cat("Murka")]
for a in animals:
    print(a.speak())     # each says its own thing

The function doesn't need to check if type(a) == Dog: .... It simply calls speak(), and that works for any animal — even one invented tomorrow.

In Python, polymorphism doesn't even require a common parent. It's enough for an object to have the right method. This is called duck typing: "if it quacks like a duck, it's a duck".

class File:
    def read(self): ...

class Socket:
    def read(self): ...

def load(source):      # any object with a read() method will do
    return source.read()

A built-in example: len() works with strings, lists and dictionaries — each type has its own __len__.

Task. Create classes Square(side) and Circle(radius) with an area() method. Use math.pi for the circle. Then write a function total_area(shapes) that adds up the areas of any shapes in the list.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.