

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Polymorphism
incomplete
2: Get Edges
incomplete
3: Overlap
incomplete
4: Dragon Area
incomplete
5: Polymorphism Review
incomplete
6: Operator Overloading
incomplete
7: Operator Overload Review
incomplete
8: Overriding Built-in Methods
incomplete
9: Polymorphism Practice
incomplete
10: Polymorphism Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Click to play video
While inheritance is the most unique trait of object-oriented languages, polymorphism is probably the most powerful. It also is not particularly unique to class-based languages. Polymorphism is the ability of a variable, function or object to take on multiple forms.
For example, classes in the same hierarchical tree may have methods with the same name and signature but different implementations. Here's a simple example:
class Creature:
def move(self) -> None:
print("the creature moves")
class Dragon(Creature):
def move(self) -> None:
print("the dragon flies")
class Kraken(Creature):
def move(self) -> None:
print("the kraken swims")
creatures: list[Creature] = [Creature(), Dragon(), Kraken()]
for creature in creatures:
creature.move()
# prints:
# the creature moves
# the dragon flies
# the kraken swims
Because all three classes have a .move() method, we can shove the objects into a single list, and call the same method on each of them, even though the implementation (method body) is different.
This idea is sometimes referred to as "duck typing". If it looks like a duck, swims like a duck, and quacks like a duck, it's a duck. Or, in our example, if it has a .move() method, we can treat it like a Creature.
Let's build some hit-box logic for our game, starting with a simple Rectangle.
Complete the __init__(self, x1: int, y1: int, x2: int, y2: int) -> None method. Configure the class to have properties matching the variables passed into the constructor in this order:
x1y1x2y2