Polymorphism is a core concept in Object-Oriented Programming (OOP) that comes from the Greek words Poly (many) and Morph (forms). In Python, it refers to the ability of different classes to be treated as instances of the same general class through a single interface.
Polymorphism allows a single function, method, or operator to behave differently depending on the object it is acting upon.
Example: The len() function is polymorphic. It can take a string and return the number of characters, or it can take a list and return the number of elements. The "interface" is the same (len()), but the internal logic changes based on the data type.
Duck Typing: "If it walks like a duck and quacks like a duck, it’s a duck." Python doesn't care about the object's type, only whether it has the required methods.
Method Overriding: A child class provides a specific implementation of a method that is already defined in its parent class.
Operator Overloading: Using the same operator (like +) for different purposes (e.g., adding numbers vs. concatenating strings).
We can create a function that takes any object and calls a method on it, regardless of the object's class.
class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" # This function is polymorphic def animal_sound(animal): print(animal.speak()) dog = Dog() cat = Cat() animal_sound(dog) # Output: Woof! animal_sound(cat) # Output: Meow!
This is common when multiple child classes inherit from a parent but need to perform the same action in different ways.
class Shape: def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * (self.radius ** 2) class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side * self.side shapes = [Circle(5), Square(4)] for shape in shapes: print(f"Area: {shape.area()}")
| Feature | Description |
| Interface | The method name remains the same (e.g., .speak() or .area()). |
| Flexibility | Allows you to write code that can handle new class types without modification. |
| Relationship | Often works hand-in-hand with Inheritance (Overriding). |
Simplicity: You don't need to check the type of an object (if isinstance...) before calling a method.
Scalability: You can add a new class (e.g., class Triangle) to your project, and any polymorphic functions you already wrote will work with it automatically.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION