What is Polymorphism in Python with example | Duck typing
Polymorphism in Python refers to the ability of an object to take on different forms or behaviors depending on the context in which it is used. It is one of the fundamental principles of object-oriented programming (OOP) and allows objects of different classes to be treated as if they were objects of a common superclass.
Polymorphism is closely related to inheritance, which is another important concept in OOP. In Python, when a class inherits from another class, it inherits not only the attributes and methods of the parent class but also the ability to be polymorphic.
What is polymorphism in Python?
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class. In Python, polymorphism is achieved through method overriding and dynamic dispatch, which means that you can call a method on an object, and the specific implementation of that method is determined at runtime based on the actual type of the object.
Polymorphism enables you to write more generic and reusable code, as you can work with objects of different classes in a consistent way, as long as they share a common interface (methods and attributes).
Polymorphism in Python with example
Here’s an example demonstrated in Python:
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
class Bird(Animal):
def make_sound(self):
print("Chirp!")
# Polymorphic function
def animal_sounds(animals):
for animal in animals:
animal.make_sound()
# Create instances of different animals
dog = Dog()
cat = Cat()
bird = Bird()
# Create a list of animal objects
animals = [dog, cat, bird]
# Call the polymorphic function with the list of animals
animal_sounds(animals)
In the above polymorphism in Python example, we have a base class Animal
with a method make_sound()
. The subclasses Dog
, Cat
and Bird
inherit from Animal
and override the make_sound()
method with their own implementations.
The function animal_sounds()
takes a list of animal objects as input. It iterates over the list and calls the make_sound()
method on each animal object. The key point here is that the method call is polymorphic, meaning that the appropriate implementation make_sound()
is determined at runtime based on the actual type of each object in the list.
When you run the code, it will produce the following output:
Woof! Meow! Chirp!
Types of Polymorphism in Python
There are two main forms of polymorphism in Python:
- Method Overriding: Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its parent class. The method in the subclass must have the same name and the same number and type of parameters as the method in the parent class. When the method is called on an object of the subclass, the overridden method in the subclass is executed instead of the method in the parent class.
Here’s an example:
class Animal:
def speak(self):
passclass Dog(Animal):
def speak(self):
return “Woof!”class Cat(Animal):
def speak(self):
return “Meow!”my_dog = Dog()
my_cat = Cat()print(my_dog.speak()) # Output: “Woof!”
print(my_cat.speak()) # Output: “Meow!”
- Duck Typing: Method overloading refers to the ability to define multiple methods with the same name but different parameters in a class. However, unlike some other programming languages, Python does not directly support method overloading by default. In Python, you can achieve a similar effect by using default parameter values or by using variable-length arguments (*args or **kwargs) to accept a variable number of arguments.
Here’s an example of duck typing:
class Car:
def drive(self):
print(“Car is driving.”)class Bike:
def drive(self):
print(“Bike is riding.”)def start_vehicle(vehicle):
vehicle.drive()my_car = Car()
my_bike = Bike()start_vehicle(my_car) # Output: “Car is driving.”
start_vehicle(my_bike) # Output: “Bike is riding.”
Class polymorphism in Python refers to the ability of different classes to have methods with the same name but different implementations. It allows objects of different classes to be treated as if they were objects of a common superclass, enabling code reuse and flexibility.
To demonstrate class polymorphism in Python, let’s consider an example using geometric shapes:
class Shape:
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius**2
# Create instances of different shapes
rectangle = Rectangle(5, 3)
circle = Circle(2)
# Call the polymorphic method
print(rectangle.calculate_area()) # Output: 15
print(circle.calculate_area()) # Output: 12.56