Literally, "polymorphism" means "many forms". In programming, the term describes methods, functions or operators that share a name but can run on many different objects or classes.
Function Polymorphism
The built-in len() function is a good Python example, since it works on objects of different types.
Example
Given a string, len() counts its characters:
Output: complete Python program
x = "Hello World!"
print(len(x))
Example
Given a tuple, len() counts its items:
Output: complete Python program
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
Example
Given a dictionary, len() counts its key/value pairs:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Class Polymorphism
Class methods are a common home for polymorphism: several classes can each define a method with the same name.
Suppose the classes Car, Boat and Plane each have their own move() method:
Notice the for loop at the end of the code. Polymorphism is what lets it run the same method on objects of all three classes.
Example
Three classes that share a method name:
Output: complete Python program
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!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car object
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object
for x in (car1, boat1, plane1):
x.move()
Inheritance Class Polymorphism
Does this also work with child classes that share a method name? It does.
Take the classes above and add a parent class, Vehicle, with Car, Boat and Plane as its children. Each child receives the Vehicle methods and may override them:
A child class takes on the properties and methods of its parent.
Look at Car in the example: it has an empty body, yet it still gets brand, model and move() from Vehicle.
Boat and Plane get the same three members from Vehicle too, but each replaces move() with an override of its own.
Thanks to polymorphism, one method call works across all of these classes.
Example
Add a parent class called Vehicle and derive Car, Boat and Plane from it:
Output: complete Python program
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car object
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object
for x in (car1, boat1, plane1):
print(x.brand)
print(x.model)
x.move()