Skip to main content

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:

Prompt
Write a Python program that uses len() on the string "Hello World!" and prints the result.
Output: complete Python program

Example

Given a tuple, len() counts its items:

Prompt
Write a Python program that uses len() on a tuple of three fruits and prints the result.
Output: complete Python program

Example

Given a dictionary, len() counts its key/value pairs:

Prompt
Write a Python program that uses len() on a dictionary with brand, model, and year keys and prints the result.
Output: complete Python program

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:

Prompt
Write three Python classes Car, Boat, and Plane each with a move() method that prints different actions. Create objects and loop through them calling move().
Output: complete Python program

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:

Prompt
Write a Vehicle parent class with a move() method, and Car, Boat, Plane child classes where Boat and Plane override move(). Loop through objects printing brand, model, and calling move().
Output: complete Python program