Understanding Python Polymorphism: A Comprehensive Guide

Understanding Python Polymorphism: A Comprehensive Guide

The term "polymorphism" means "many forms" and, in programming, it refers to methods, functions, or operators that share the same name but can be executed on different objects or classes. This article will explore the concept of polymorphism in Python, illustrating its usage through practical examples.

Function Polymorphism

One of the simplest examples of polymorphism in Python is the len() function, which can be used on different object types.

Example: Using len() with a String

x = "Hello, World!"
print(len(x))

Example: Using len() with a Tuple

my_tuple = ("apple", "banana", "cherry")
print(len(my_tuple))

Example: Using len() with a Dictionary

my_dict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(len(my_dict))

Class Polymorphism

Polymorphism is often employed in class methods, where multiple classes can define methods with the same name. For example, consider three classes: Car, Boat, and Plane, each with a method called move().

Example: Different Classes with the Same Method

class Car:
def __init__(self, brand):
self.brand = brand
def move(self):
return "Driving!"

class Boat:
def __init__(self, brand):
self.brand = brand
def move(self):
return "Sailing!"

class Plane:
def __init__(self, brand):
self.brand = brand
def move(self):
return "Flying!"

Example: Using the Classes

vehicles = [Car("Ford"), Boat("Yamaha"), Plane("Boeing")]
for vehicle in vehicles:
print(vehicle.move())

Inheritance and Polymorphism

Polymorphism can also be applied in the context of inheritance. Child classes can inherit methods from a parent class and override them as needed.

Example: Parent Class and Child Classes

class Vehicle:
def __init__(self, brand):
self.brand = brand
def move(self):
return "Moving!"

class Car(Vehicle):
def move(self):
return "Driving fast!"

class Boat(Vehicle):
def move(self):
return "Sailing smoothly!"

Example: Using the Inherited Classes

vehicles = [Car("Ford"), Boat("Yamaha")]
for vehicle in vehicles:
print(vehicle.brand + ": " + vehicle.move())

Exercise

True or False: One object cannot have a method with the same name as another object's method.

  • True
  • False

Conclusion

In this guide, we explored the concept of polymorphism in Python, including function polymorphism and class polymorphism. We learned how polymorphism allows different classes to define methods with the same name and how inheritance plays a role in this flexibility. Understanding polymorphism is essential for writing clean and efficient Python code.