Polymorphism in Python
Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows methods to do different things based on the object that it is acting upon. In Python, polymorphism allows objects of different classes to be treated as objects of a common superclass. The most common use of polymorphism is when different classes have methods with the same name but behave differently.
Types of Polymorphism
- Compile-time Polymorphism: Achieved by method overloading and operator overloading.
- Run-time Polymorphism: Achieved by method overriding, where a child class redefines a method of its parent class.
Example of Polymorphism
This example demonstrates run-time polymorphism using method overriding.
Code Example
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
# Function to demonstrate polymorphism
def animal_sound(animal):
print(animal.sound())
dog = Dog()
cat = Cat()
animal_sound(dog) # Dog's sound
animal_sound(cat) # Cat's sound
Output
Meow
Conclusion
Polymorphism is a powerful feature in Python that enhances the flexibility and maintainability of code. By allowing the same method to behave differently based on the object it is called on, polymorphism promotes a clean and understandable code structure, making it easier to manage and extend.