Polymorphism In Python
Python Polymorphism: Comprehensive Theory
The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or types.
1. Function Polymorphism
An example of a Python function that can be used on different objects is the len() function.
For Strings:
It returns the number of characters:
x = "Hello World!"
print(len(x)) # Output: 12
For Tuples:
It returns the number of items in the tuple:
mytuple = ("apple", "banana", "cherry")
print(len(mytuple)) # Output: 3
2. Class Polymorphism
Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
car1 = Car("Ford", "Mustang")
boat1 = Boat("Ibiza", "Touring 20")
for x in (car1, boat1):
x.move()
Look at the for loop at the end. Because of polymorphism we can execute the move() method for both classes.
3. Inheritance Polymorphism
What about classes with child classes with the same name? Can we use polymorphism there?
Yes. We can use inheritance polymorphism.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
def move(self):
print("Drive!")
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")
for x in (car1, boat1, plane1):
x.move()
Child classes inherit the properties and methods from the parent class. In the example above, Car, Boat, and Plane override the move() method of the Vehicle class, but they all share the same method name.
4. Why Use Polymorphism?
Polymorphism allows for code flexibility and reusability. You can write a single function or loop that can process many different types of objects as long as they provide the expected method name.