What is Polymorphism in Python: Simple Explanation and Example
polymorphism means that different objects can be accessed through the same interface, allowing the same function or method to work with different types of objects. It lets you use a single function name to perform different tasks depending on the object it is working with.How It Works
Polymorphism in Python works like a universal remote control that can operate different devices such as a TV, DVD player, or sound system. Even though each device is different, the remote uses the same buttons to control them. Similarly, polymorphism allows different objects to respond to the same function call in their own way.
For example, if you have a function that calls a method named make_sound(), different objects like a dog or a cat can have their own version of make_sound(). When you call this method, the correct sound for each animal plays without changing the function itself.
Example
This example shows two classes, Dog and Cat, each with their own make_sound() method. The animal_sound() function calls make_sound() on any object passed to it, demonstrating polymorphism.
class Dog: def make_sound(self): return "Woof!" class Cat: def make_sound(self): return "Meow!" def animal_sound(animal): print(animal.make_sound()) dog = Dog() cat = Cat() animal_sound(dog) animal_sound(cat)
When to Use
Use polymorphism when you want to write flexible and reusable code that can work with different types of objects without knowing their exact class. It is especially useful in large programs where many objects share similar behavior but implement it differently.
For example, in a game, you might have different characters like players, enemies, and NPCs that all have an attack() method. Polymorphism lets you call attack() on any character without checking its type, making your code cleaner and easier to maintain.
Key Points
- Polymorphism means many forms, allowing one interface to control different data types.
- It helps write code that is easier to extend and maintain.
- Commonly used with methods that have the same name but different behaviors in different classes.
- Supports the concept of "one function, many behaviors".