[NOTE] Polymorphism
01 January 2024 | 2 min read
Notes on polymorphism in programming
Polymorphism is about writing code that can work with different kinds of objects through a common interface. The interface provides the “structure”, the implementation happens in the class itself.
Key ideas
- Classes and methods:
- A class bundles data (attributes) and behavior (methods).
- Different classes can define methods with the same name but different internal details. (Function signature is identical, although implementation differs.)
- Polymorphism (“many forms”):
- Writing code that expects an object with a certain method (like .move(), .process(), .getById()), not a specific class.
- Any object that provides the expected method can be used in that place.
- This often removes the need for long chains of if/else checks.
- Encapsulation (supporting concept):
- Each class hides its internal details behind methods (e.g. private properties hidden behind getters and/or methods).
- Polymorphism build on this: callers only care about what a method does, not how it does it.
Example
class NpcMage:
def move(self, x, y) -> tuple[int, int]:
"""
Move character INSTANTLY on x/y axis by the amount passed in the params.
:param x: Distance to move on the x axis
:param y: Distance to move on the y axis
:return: A tuple containing the new x/y axis positions.
"""
self._teleport(x, y)
return (self._pos_x, self._pos_y)
class NpcSoldier:
def move(self, x, y) -> tuple[int, int]:
""" Move character STEP BY STEP [...] """
self._walk(x, y)
return (self._pos_x, self._pos_y)
# Some other file
orc = NpcSoldier(0, 0)
elf = NpcMage(0, 0)
entities = [orc, elf]
for entity in entities:
entity.move(5, 7)
In this case we don’t need to care about the internals as the caller of the function. We know that we want the character to move on the board/field and therefore call the move() method. How the character moves doesn’t matter as long as the method signature is identical.