Polymorphism in Python
Polymorphism is when the same method name behaves differently for different classes. In the code, the move() method is implemented in Car, Boat, and Plane, and when we call x.move() in a loop, each object responds according to its class. This allows the same interface to work for multiple types of objects.
Python Example
class Automobile:
def __init__(self, make, type_model):
self.make = make
self.type_model = type_model
def go(self):
print("Driving on the road!")
class Ship:
def __init__(self, make, type_model):
self.make = make
self.type_model = type_model
def go(self):
print("Sailing on the water!")
class Aircraft:
def __init__(self, make, type_model):
self.make = make
self.type_model = type_model
def go(self):
print("Flying in the sky!")
# Create objects
auto1 = Automobile("Tesla", "Model S")
ship1 = Ship("Yamaha", "WaveRunner")
plane1 = Aircraft("Airbus", "A320")
# Call the move/go method for each object
for vehicle in (auto1, ship1, plane1):
vehicle.go()
What is Polymorphism?
Polymorphism means “many forms”.
In object-oriented programming, it allows different classes to have methods with the same name, but each class can implement it differently.
Key idea:
- The same method call can behave differently depending on the object type.
How it’s Used
Python allows polymorphism: the same method call works for different objects.
for x in (car1, boat1, plane1):
x.move()
Here, x.move() works for all objects. Python dynamically determines which move() to call based on the actual object type.
The same code produces different outputs depending on the object:
Drive! Sail! Fly!