Polymorphism is an important concept in object-oriented programming (OOP). It allows objects of different classes to be treated as objects of a common superclass. Polymorphism in Python enables methods in different classes to have the same name but behave differently.
What is Polymorphism?
Polymorphism means “many forms.” In programming, it allows methods with the same name to perform different tasks depending on the context or object.
Example of Polymorphism in Real Life
- The action “run” has different meanings depending on the subject:
- A person running means physical movement.
- A program running means execution on a computer.
Types of Polymorphism in Python
- Method Overriding (Inheritance)
- Method Overloading (Function Arguments)
- Polymorphism with Functions and Classes
1. Method Overriding (Polymorphism in Inheritance)
In method overriding, a child class provides a specific implementation of a method that is already defined in its parent class.
class Animal:
def sound(self):
print("Animals make sound.")
class Dog(Animal):
def sound(self):
print("Dogs bark.")
class Cat(Animal):
def sound(self):
print("Cats meow.")
# Create objects
dog = Dog()
cat = Cat()
# Call the overridden method
dog.sound() # Outputs: Dogs bark.
cat.sound() # Outputs: Cats meow.
How It Works
- The
sound
method is present in both theAnimal
class and the child classes (Dog
,Cat
). - The child classes override the
sound
method to provide their specific implementations.
2. Method Overloading
In Python, method overloading (multiple methods with the same name but different arguments) is not supported directly. However, you can achieve similar behavior by using default arguments or variable-length arguments (*args
and **kwargs
).
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
calc = Calculator()
# Call the same method with different numbers of arguments
print(calc.add(5)) # Outputs: 5
print(calc.add(5, 10)) # Outputs: 15
print(calc.add(5, 10, 15)) # Outputs: 30
How It Works
- The
add
method accepts optional arguments (b
andc
) with default values of0
. - Depending on the number of arguments passed, the method performs the corresponding addition.
3. Polymorphism with Functions and Classes
Polymorphism in Python allows the same function to operate on objects of different classes if they have the same method or attribute.
class Bird:
def fly(self):
print("Birds can fly.")
class Penguin:
def fly(self):
print("Penguins cannot fly but can swim.")
# A function that demonstrates polymorphism
def flying_test(bird):
bird.fly()
# Objects
sparrow = Bird()
penguin = Penguin()
# Call the same function with different objects
flying_test(sparrow) # Outputs: Birds can fly.
flying_test(penguin) # Outputs: Penguins cannot fly but can swim.
How It Works
- The
flying_test
function calls thefly
method on any object passed to it. - It works correctly for both
Bird
andPenguin
, demonstrating polymorphism.
4. Polymorphism in Abstract Classes
An abstract class defines methods that must be implemented in derived classes. This is useful for ensuring that a method exists in all child classes, making polymorphism easier.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
def perimeter(self):
return 2 * (self.length + self.breadth)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
# Objects
rect = Rectangle(4, 5)
circle = Circle(7)
# Polymorphism with abstract class
print("Rectangle Area:", rect.area()) # Outputs: 20
print("Rectangle Perimeter:", rect.perimeter()) # Outputs: 18
print("Circle Area:", circle.area()) # Outputs: 153.86
print("Circle Perimeter:", circle.perimeter()) # Outputs: 43.96
How It Works
- The
Shape
class enforces the implementation ofarea
andperimeter
methods in derived classes (Rectangle
andCircle
). - Both classes implement the methods differently, demonstrating polymorphism.
Advantages of Polymorphism
- Code Flexibility: Functions and methods work with different object types.
- Code Reusability: Write once, and use with multiple classes.
- Extensibility: Add new functionality without modifying existing code.
Summary
- Polymorphism allows the same interface to be used for different data types or classes.
- It is implemented through method overriding, overloading, and using abstract classes.
- Polymorphism enhances code flexibility and reusability.