Python Polymorphism

Python Polymorphism

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 classes.


Function Polymorphism

An example of a Python function that can be used on different objects is the len() function.

Class Polymorphism

Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.

For example, say we have three classes: Car, Boat, and Plane, and they all have a method called move():

Polymorphism Example

class Car:
  def move(self):
    print("Drive!")

class Boat: def move(self): print("Sail!")

class Plane: def move(self): print("Fly!")

car1 = Car() boat1 = Boat() plane1 = Plane()

for x in (car1, boat1, plane1): x.move()


Exercise

?

What does Polymorphism mean in the context of Object-Oriented Programming?