Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. In Python, polymorphism enables you to write more flexible and reusable code.
The term "polymorphism" comes from Greek, meaning "many forms." In Python, it refers to the ability of different objects to respond to the same method call in ways specific to their individual classes. This concept is closely related to Python Inheritance.
Python uses duck typing, which focuses on the behavior of an object rather than its type. If an object has the required methods and properties, it can be used regardless of its actual type.
def make_sound(animal):
animal.sound()
class Dog:
def sound(self):
print("Woof!")
class Cat:
def sound(self):
print("Meow!")
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Woof!
make_sound(cat) # Output: Meow!
Method overriding is another form of polymorphism where a subclass provides a specific implementation for a method that is already defined in its superclass.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
animal = Animal()
dog = Dog()
animal.speak() # Output: Animal speaks
dog.speak() # Output: Dog barks
Polymorphism is a powerful feature in Python that enhances code flexibility and reusability. By understanding and applying polymorphic principles, you can create more robust and maintainable Python programs. It's an essential concept to master for effective object-oriented programming in Python.
To further explore related concepts, check out Python Classes and Objects and Python Encapsulation.