Understanding Python Polymorphism with Practical Examples









Understanding Python Polymorphism with Practical Examples

Understanding Python Polymorphism with Practical Examples

In object-oriented programming, the concept of polymorphism allows methods, functions, or operators with the same name to behave differently based on the object they operate on. The term itself is derived from Greek, meaning “many forms,” and is foundational in writing flexible and maintainable code in Python.

Function Polymorphism

A classic example of function polymorphism in Python is the built-in len() function. This function adapts its behavior based on the data type of the object it is applied to.

On Strings

The len() function returns the number of characters in a string:

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

On Tuples

For a tuple, it returns the number of elements:

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

On Dictionaries

When used on dictionaries, it returns the count of key-value pairs:

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

Class-Based Polymorphism

Polymorphism also applies to methods in multiple classes. If several classes implement a method with the same name, Python can call the appropriate version based on the object’s type at runtime.

Example: Car, Boat, Plane

Each class implements a method named move():

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")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")

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

Despite sharing the same method name, each object’s move() function behaves uniquely. This is the essence of polymorphism in object-oriented design.

Polymorphism Through Inheritance

Another common scenario involves parent and child classes. A child class can inherit behavior from a parent class and optionally override it to implement its own version.

Example Using a Parent Class: Vehicle

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")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")

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

In this example, Car does not override the move() method and therefore inherits the implementation from the Vehicle class. In contrast, Boat and Plane override the method, showcasing polymorphic behavior through inheritance.

Conclusion

Polymorphism is a vital concept in Python and supports writing code that is clean, maintainable, and scalable. Whether you are using built-in functions or creating class hierarchies, understanding polymorphism enhances your ability to build robust software systems.

This educational content is brought to you by Devyra, your go-to resource for mastering programming concepts with clarity and precision.


More From Author

Python Iterators Explained: Complete Guide with Examples

Understanding Python Scope: Local, Global, and Nonlocal Variables

Leave a Reply

Your email address will not be published. Required fields are marked *