Polymorphism means "many forms". In Python, it allows the same function name or operator to work in different ways depending on the context (the data type or the class that uses it).
This makes code more flexible, easier to extend, and more readable because you can use the same interface for different underlying implementations.
len() work with strings, lists, dictionaries, and more.sound()), but each provides its own implementation.There is no special keyword for polymorphism in Python. It naturally appears in:
As long as an object provides the expected method or operation, it can be used in a polymorphic way.
Functions like len() work on different data types in different ways.
print(len("Hello")) # 5 (string length)
print(len([1, 2, 3])) # 3 (list length)
print(len({"a": 1, "b": 2})) # 2 (dictionary keys count)
Different classes can have methods with the same name, but their behaviors can be different. You can then loop over a collection of objects and call the same method on each one.
class Dog:
def sound(self):
return "Bark" # Dog's sound implementation
class Cat:
def sound(self):
return "Meow" # Cat's sound implementation
animals = [Dog(), Cat()] # List of animal objects
for animal in animals:
print(animal.sound()) # Polymorphic method call
Inheritance allows child classes to override parent methods, providing specific implementations.
class Bird:
def fly(self):
print("Most birds can fly")
class Penguin(Bird):
def fly(self):
print("Penguins cannot fly")
bird = Bird()
penguin = Penguin()
bird.fly() # Most birds can fly
penguin.fly() # Penguins cannot fly
len("Hello") → 5 because the string has 5 characters.len([1, 2, 3]) → 3 because the list has 3 elements.len({"a": 1, "b": 2}) → 2 because the dictionary has 2 keys.Dog / Cat example, both classes define sound(), so the loop can call animal.sound() without caring which class the object belongs to.Bird / Penguin example, Penguin overrides fly() and changes the behavior while still using the same method name.sound(), draw(), move()) for consistency.Car and Bike classes, both with a move() method. Put their objects in a list and call move() in a loop.Bird and Penguin).+ operator by adding: