Browser lab18 min+60 XP

Polymorphism

One command, many behaviours. Loop through mixed objects and let each do its own thing.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Different objects can answer the same method call in their own way.

Key words
for shape in shapes:shape.area()Circle(1).area()3.1Square(3).area()9Circle(2).area()12.6each object answers its own waysame call
The same call, area(), gives each shape its own answer.

Polymorphism means "many shapes". Different classes can have methods with the same name, so the same line of code does the right thing for each object: for shape in shapes: print(shape.area()) works whether each shape is a Circle or a Square.

Python goes further with duck typing: "if it walks like a duck and quacks like a duck, it is a duck". Python does not check the class at all. Any object with the right method works, even if the classes are not related.

This makes code flexible: you can add a new kind of shape later without changing the loop.

Real life linkPress play on a song, a video or a podcast and each one does the right thing, even though the button is the same. That is polymorphism.
Example code
class Circle:
    def __init__(self, r):
        self.r = r
    def area(self):
        return round(3.14159 * self.r ** 2, 1)

class Square:
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

for shape in [Circle(1), Square(3), Circle(2)]:
    print(type(shape).__name__, shape.area())
TASK 2

Try it yourself

+10 XP

Write two classes, Duck and Robot, that are not related but both have a quack() method (returning Quack! and BEEP. QUACK.). Loop through one of each and print what they say.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What is the idea called where Python only cares whether an object has the right method, not its class? (two words)

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Zoo feeding time

+20 XP

Write a parent Animal class with a feed() method returning The animal eats, and three subclasses (Lion, Penguin, Parrot) that override it with their own messages. Put one of each in a list and loop through it calling feed(). Then add a ZooKeeper class (not an Animal) that also has feed(), and show it works in the same loop.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.