Polymorphism
One command, many behaviours. Loop through mixed objects and let each do its own thing.
Code runs right here in your browser. Nothing to install.
Learn it
Different objects can answer the same method call in their own way.
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.
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())
Try it yourself
+10 XPWrite 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.
Capture the flag
+10 XPWhat 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.
Zoo feeding time
+20 XPWrite 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.