

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
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
The Greek roots of the word "polymorphism" are:
Polymorphism in programming is the ability to present the same interface (function or method signatures) for many different underlying forms (data types).
A classic example is a Shape class that Rectangle, Circle, and Triangle can inherit from. Each has different underlying data:
Polymorphism is where each type is responsible for its own data and code, but still adheres to the same interface, in this case a simple method "signature":
def draw_shape(self) -> str:
So now we can treat shapes as the same even though they are different. It hides the complexities of the difference behind a clean abstraction.
shapes: list[Circle | Rectangle] = [Circle(5, 5, 10), Rectangle(1, 3, 5, 6)]
for shape in shapes:
print(shape.draw_shape())
A function signature (or method signature) includes the name, inputs, and outputs of a function or method. For example, hit_by_fire in the Human and Archer classes have identical signatures.
class Human:
def hit_by_fire(self) -> int:
self.health -= 5
return self.health
class Archer:
def hit_by_fire(self) -> int:
self.health -= 10
return self.health
Both methods have the same name, take no additional inputs, and return integers. If any of those things were different, they would have different function signatures. Here are methods with different signatures:
class Human:
def hit_by_fire(self) -> int:
self.health -= 5
return self.health
class Archer:
def hit_by_fire(self, dmg: int) -> int:
self.health -= dmg
return self.health