Polymorphism
Polymorphism is a Greek word meaning "many forms." In Python, it refers to the ability of different objects to respond to the same method call in their own...
Polymorphism in Python: One Interface, Many Forms
Polymorphism is a Greek word meaning "many forms." In Python, it refers to the ability of different objects to respond to the same method call in their own way. This is one of the most powerful aspects of OOP because it allows you to write code that works with objects of different types without needing to know the exact type in advance.
Python achieves polymorphism naturally through its duck typing system. If an object has a method with the right name, Python will call it, regardless of what class that object belongs to. This is summarized by the saying: "If it walks like a duck and quacks like a duck, it is a duck."
class Dog: def speak(self): return "Woof!"
class Cat: def speak(self): return "Meow!"
class Bird: def speak(self): return "Tweet!"
animals = [Dog(), Cat(), Bird()] for animal in animals: print(animal.speak())
This loop calls speak on each object without checking its type. Each object responds with its own version of the method. This is polymorphism in action. You can add a new animal class later with its own speak method, and the loop will handle it without any changes.
Polymorphism also works when classes share a common parent and override inherited methods. This is method overriding. The child class provides its own implementation, and Python calls the right one based on the actual type of the object at runtime.
Python's built-in functions also rely on polymorphism. The len function, for example, works on strings, lists, dictionaries, and custom objects that define __len__. The print function works with any object that defines __str__. This is why Python code tends to be concise and composable.
Interview tip: Be ready to distinguish between compile-time polymorphism (method overloading, not natively supported in Python) and runtime polymorphism (method overriding via inheritance or duck typing). Python favors runtime polymorphism and uses duck typing rather than strict type hierarchies.