Polymorphism in Python – How to Become Master in Method & Class

Imagine you have a program with classes representing a Car, a Boat, and a Plane. Each class has a method called move(). Even though they share the same method name, when you call move() on a Car object, it drives; on a Boat object, it sails; and on a Plane object, it flies. This ability for different objects to respond to the same method name in their own way is what we call polymorphism in Python.

In simple terms, polymorphism allows you to use a common interface (method name) across different classes, and each class can implement that interface in its own specialized manner. It makes your code more flexible and versatile, allowing you to work with diverse objects in a unified way.

Lets take an Example of a Python function that can be used on different objects – len() function.

x = "Hello World!"


print(len(x))

in the above code len() function will return number of characters.

Similarly if we take a example of tuple then len() function will be used to return the number of items in the tuple check below the code

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


print(len(mytuple))

Polymorphism is commonly applied in class methods, enabling the existence of multiple classes sharing the same method name.

For instance, consider three classes: Car, Boat, and Plane, each equipped with 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") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class

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

Lets break down each part of code and understand it:

Class Definations:

class Car:

def __init__(self, brand, model):
self.brand = brand
self.model = model

def move(self):
print("Drive!")
  • Defines a class Car.
  • __init__ is a special method in Python, called a constructor, which initializes the attributes of the class.
  • self refers to the instance of the class, and brand and model are parameters for the constructor.
  • move is a method within the class that prints “Drive!”.

The Boat and Plane classes are similar in structure, each with its own __init__ method to initialize attributes and a move method that prints “Sail!” and “Fly!” respectively.

Instance Creation:

car1 = Car("Ford", "Mustang")

boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")
  • Creates instances of the Car, Boat, and Plane classes.
  • car1 is an instance of Car with the brand “Ford” and model “Mustang”.
  • boat1 is an instance of Boat with the brand “Ibiza” and model “Touring 20”.
  • plane1 is an instance of Plane with the brand “Boeing” and model “747”.

Iteration and Method Invocation:

for x in (car1, boat1, plane1):

x.move()
  • Creates a loop that iterates over the instances of Car, Boat, and Plane.
  • For each iteration, the move method of the respective class instance (car1, boat1, plane1) is invoked.
  • This results in printing “Drive!”, “Sail!”, and “Fly!” consecutively, showcasing polymorphism where the same method name is used for different classes.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>