Polymorphism is one of the core pillars of Object-Oriented Programming (OOP). The word itself comes from Greek: Poly (many) and Morph (forms). In programming, it means the ability of a single interface (a function, an operator, or a method) to adapt its behavior based on the type of data it is processing.
1. Duck Typing (Dynamic Polymorphism)
In languages like Python, we follow the principle: "If it walks like a duck and quacks like a duck, itβs a duck." This means we don't care about the object's class; we only care if it has the methods we need.
2. Method Overriding (Inheritance-based)
This occurs when a Child Class provides a specific implementation of a method that is already defined in its Parent Class. This allows you to treat a group of different objects as if they were the same parent type while still getting specific behavior.
3. Operator Polymorphism
This is the simplest form. A single symbol (operator) performs different actions depending on the operands.
4. Method Overloading
This allows a class to have multiple methods with the same name but different arguments (either in number or type).
Note: Python does not support traditional method overloading (like Java or C++) directly. If you define two functions with the same name, the second one replaces the first. However, we achieve this using Default Arguments or *args.
class Logger:
def log(self, message, level="INFO"):
print(f"[{level}]: {message}")
l = Logger()
l.log("System started") # One argument
l.log("Connection failed", "ERROR") # Two arguments
Since we have worked with FastAPI, we have noticed polymorphism in action with Dependency Injection. When you define a dependency, FastAPI doesn't care exactly how the class is structured inside, as long as it returns the expected type or object for your route.
Top comments (0)