Python Polymorphism: Understanding Methods and Functions

Polymorphism in Python allows methods and functions to operate on different objects or classes with the same name. This concept, meaning "many forms," is illustrated by functions like len(), which can be used on various data types such as strings. Learn how Python implements polymorphism to enhance code flexibility and reusability.



Python Polymorphism

The word "polymorphism" means "many forms". In programming, it refers to methods, functions, or operators with the same name that can be executed on different objects or classes.

Function Polymorphism

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

String

For strings, len() returns the number of characters:

Example

# String example
x = "Hello Universe!"

print(len(x))
        
Output

14
        

Tuple

For tuples, len() returns the number of items in the tuple:

Example

# Tuple example
mytuple = ("orange", "grape", "melon")

print(len(mytuple))
        
Output

3
        

Dictionary

For dictionaries, len() returns the number of key/value pairs in the dictionary:

Example

# Dictionary example
thisdict = {
  "brand": "Tesla",
  "model": "Model X",
  "year": 2021
}

print(len(thisdict))
        
Output

3
        

Class Polymorphism

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

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

Example

# Different classes with the same method:
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("Tesla", "Model 3")        # Create a Car object
boat1 = Boat("Yamaha", "242X")        # Create a Boat object
plane1 = Plane("Airbus", "A380")      # Create a Plane object

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

Drive!
Sail!
Fly!
        

In the for loop at the end, polymorphism allows us to execute the same method for all three classes.

Inheritance Class Polymorphism

Polymorphism can also be applied to classes with child classes sharing the same method name. If we make a parent class called Vehicle and derive Car, Boat, and Plane classes from it, the child classes inherit the Vehicle methods but can override them:

Example

# Create a Vehicle class and child classes Car, Boat, Plane
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("Tesla", "Model 3")         # Create a Car object
boat1 = Boat("Yamaha", "242X")         # Create a Boat object
plane1 = Plane("Airbus", "A380")       # Create a Plane object

for x in (car1, boat1, plane1):
    print(x.brand)
    print(x.model)
    x.move()
        
Output

Tesla
Model 3
Move!
Yamaha
242X
Sail!
Airbus
A380
Fly!
        

In this example, the Car class is empty but inherits brand, model, and move() from Vehicle. The Boat and Plane classes also inherit from Vehicle but override the move() method. Because of polymorphism, we can execute the same method for all classes.