Polymorphism in Python is a fundamental concept in object-oriented programming (OOP). It allows objects of different classes to be treated as objects of a common superclass. This is particularly useful for creating flexible and extensible code.
What is Polymorphism?
Method Overloading: This is when multiple methods have the same name but different parameters. Python does not support method overloading in the traditional sense, but it can be achieved through default arguments, variable-length arguments, or keyword arguments.
Operator Overloading: This is when operators are implemented for a class to work with objects of that class. For example,
+
can be overloaded to add two objects of a custom class.Method Overriding: This is when a subclass provides a specific implementation for a method that is already defined in its superclass.
Example
Here's a simple example of method overriding in Python:
class Animal:
def speak(self):
return "I don't know what I say"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
return animal.speak()
my_dog = Dog()
my_cat = Cat()
print(animal_sound(my_dog)) # Output: Woof!
print(animal_sound(my_cat)) # Output: Meow!
In this example, Animal
is the superclass, and Dog
and Cat
are subclasses. Each subclass overrides the speak
method to provide a specific implementation.
Further Reading
For more information on polymorphism in Python, you can read about class inheritance.