Polymorphism is an important concept of Object Oriented Programming (OOP). The word polymorphism means "many forms". In Python, the same interface, method name, or operation can work differently depending on the object or data involved.
Polymorphism allows a common operation or method name to have different behavior for different objects.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
dog = Dog()
cat = Cat()
dog.sound()
cat.sound()
Output:
Bark Meow
Different classes can define a method with the same name. The behavior can be different in each class.
class Dog:
def speak(self):
print("Dog barks")
class Cat:
def speak(self):
print("Cat meows")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
Output:
Dog barks Cat meows
A common method name can be called on different objects inside a loop. Each object provides its own implementation.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output:
Bark Meow
Polymorphism is often used with inheritance. A child class can override a method inherited from a parent class.
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output:
Bark Meow
Method overriding occurs when a child class provides its own implementation of a method defined in its parent class.
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def move(self):
print("Car is driving")
car = Car()
car.move()
Output:
Car is driving
Python often follows the principle known as duck typing. The important thing is whether an object supports the required operation, rather than whether it belongs to a particular class.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
def make_sound(animal):
animal.sound()
make_sound(Dog())
make_sound(Cat())
Output:
Bark Meow
A function can work with different objects as long as those objects provide the operation required by the function.
class Student:
def show(self):
print("Student")
class Teacher:
def show(self):
print("Teacher")
def display(obj):
obj.show()
display(Student())
display(Teacher())
Output:
Student Teacher
Python's built-in functions can often work with different types of objects. For example, len() works with strings, lists, tuples, and many other objects that provide the required interface.
print(len("Python"))
print(len([10, 20, 30]))
print(len((1, 2, 3, 4)))
Output:
6 3 4
The same operator can perform different operations depending on the data type.
print(10 + 20)
print("Hello " + "Python")
print([1, 2] + [3, 4])
Output:
30 Hello Python [1, 2, 3, 4]
The + operator performs numeric addition for numbers and concatenation for strings and lists.
class Circle:
def area(self):
print("Circle area")
class Square:
def area(self):
print("Square area")
def calculate_area(shape):
shape.area()
calculate_area(Circle())
calculate_area(Square())
Output:
Circle area Square area
Abstract base classes can define a common interface that subclasses must implement.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output:
Bark Meow
Polymorphism is useful when different classes provide the same interface. Code using the interface does not need to know the specific concrete class.
class PDF:
def print_document(self):
print("Printing PDF")
class Word:
def print_document(self):
print("Printing Word document")
documents = [
PDF(),
Word()
]
for document in documents:
document.print_document()
Output:
Printing PDF Printing Word document
class Student:
def __init__(self, name):
self.name = name
def display(self):
print("Student:", self.name)
class Teacher:
def __init__(self, name):
self.name = name
def display(self):
print("Teacher:", self.name)
people = [
Student("Rahul"),
Teacher("Amit")
]
for person in people:
person.display()
Output:
Student: Rahul Teacher: Amit
Different payment classes can provide the same pay() method while implementing different payment behavior.
class CashPayment:
def pay(self, amount):
print("Paid by cash:", amount)
class CardPayment:
def pay(self, amount):
print("Paid by card:", amount)
class UPIPayment:
def pay(self, amount):
print("Paid by UPI:", amount)
payments = [
CashPayment(),
CardPayment(),
UPIPayment()
]
for payment in payments:
payment.pay(1000)
Output:
Paid by cash: 1000 Paid by card: 1000 Paid by UPI: 1000
Polymorphism and inheritance are related but they are not the same concept.
| Inheritance | Polymorphism |
|---|---|
| Allows a class to reuse another class's behavior. | Allows different objects to respond to the same interface. |
| Creates relationships between classes. | Provides flexible behavior. |
| Uses parent and child classes. | Can work with inheritance or duck typing. |
Consider different types of vehicles. Each vehicle can have a move() method, but the way it moves can be different.
class Car:
def move(self):
print("Car drives")
class Boat:
def move(self):
print("Boat sails")
class Plane:
def move(self):
print("Plane flies")
vehicles = [
Car(),
Boat(),
Plane()
]
for vehicle in vehicles:
vehicle.move()
Output:
Car drives Boat sails Plane flies
class Employee:
def work(self):
print("Employee is working")
class Developer(Employee):
def work(self):
print("Developer writes code")
class Teacher(Employee):
def work(self):
print("Teacher teaches students")
class Manager(Employee):
def work(self):
print("Manager manages the team")
employees = [
Developer(),
Teacher(),
Manager()
]
for employee in employees:
employee.work()
Output:
Developer writes code Teacher teaches students Manager manages the team
Question: What does polymorphism allow in Python?