Polymorphism is the ability of a variable, function or object to take on multiple forms in source
- “poly” = “many”
- “morph” = “form”
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 swimsBecause 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.