4 Ways of implementing Polymorphism in Python
Introduction
Polymorphism is a feature of computer languages that enables functions to be implemented in several ways. The ability of a single function to perform multiple tasks makes it a powerful tool for developers. It also helps reduce the complexity of a program and improve its readability. In this blog, we are discussing the various ways of implementing polymorphism in Python.
What is polymorphism in python?
Polymorphism in Python is the ability of a program to be useful with different types of data. Using it, programmers may create code that can be applied to a wide variety of object types. This makes complex operations easier and improves how well the program runs. Polymorphism consists of two important concepts: inheritance and overriding, which are made possible by the capabilities of the Python language.
How to use polymorphism?
Polymorphism allows us to utilize the same function name for multiple tasks. The operation performed by the function depends upon the type of data passed as parameters to the function. The developer needs only to make sure that the parameters passed are the same type. Polymorphism can be implemented by using either subtyping or duck typing.
Python has four ways to implement polymorphism
Duck Typing
In duck
typing language, objects are typed based on the interface to which they adhere rather than their class. Duck
typing is a way to check if an object has the methods needed for a certain task in Python. If it does, then the program can execute the task, regardless of the type of object.
Method Overloading
Method overloading is a feature that enables the same method name to be used with various arguments. When a method is invoked with its arguments specified, it is really invoked in its most precise form. As a result, the code becomes more readable and has less duplication.
Operator Overloading
By linking an operator to one or more classes, developers can change how different operators work. Because of this polymorphism, programmers may reuse the same operators across a wide range of scenarios.
Method Overriding
With the help of the method overriding feature, a subclass may change the way a method defined by its parent class operates. This is done by declaring the same method name with the same arguments in the subclass as in the superclass. By overriding methods, developers can customize a sub-class for special tasks.
Example of implementing polymorphism
Ducking type
Duck
typing is a programming style that allows an object to be used in the same way as another object, as long as it has the same methods and properties. In other words, the object’s type is not important; only the methods and properties it has are important.
Code:
class Duck:
def quack(self):
print("Quack quack!")
class Goose:
def quack(self):
print("Honk honk!")
def make_animal_sound(animal):
animal.quack()
duck = Duck()
goose = Goose()
make_animal_sound(duck) # Outputs: "Quack, quack!"
make_animal_sound(goose) # Outputs: "Honk honk!"
Code language: Python (python)
In this example, the make_animal_sound()
function takes an animal object as an argument and calls the quack()
method on it. The Duck and Goose classes both have a quack()
method, so they can be used with the make_animal_sound()
function. This is an example of duck typing because the object’s type (Duck or Goose) is not important; only the presence of the quack()
method is important.
Output
Method Overloading
Using the programming concept of “method overloading,” a class may have numerous methods with the same name but with distinct arguments. When a method is called, the compiler selects which version of the method to run depending on the amount and type of arguments given.
Code:
class Calculator:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
calculator = Calculator()
print(calculator.add(1, 2)) # Outputs: 3
print(calculator.add(1, 2, 3)) # Outputs: 6
Code language: Python (python)
In this example, the Calculator class contains two add()
methods: one that accepts two parameters and one that takes three arguments. When the add()
method is invoked with two parameters, the first version of the method is run, and when it is called with three arguments, the second version is called. Method overloading occurs when two or more methods have the same name but take distinct arguments.
Output
Operator Overloading
Using a programming method known as “operator overloading,” familiar operators (such as +, -, *, etc.) may take on several meanings in various settings. This is often used to make operations on objects more straightforward to understand or more helpful.
Code:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) # Outputs: "(4, 6)"
Code language: Python (python)
In this example, the Vector
class represents a two-dimensional vector with x
and y
components. The __add__()
method overloads the +
operator to add two vectors together by adding their respective components. The __str__()
method is used to provide a string representation of the vector for printing.
When the +
operator is used on two Vector
objects (v1
and v2
), the __add__()
method is called to perform the addition and return a new Vector
object (v3
). This is an example of operator overloading because the +
operator takes on a new meaning when used on Vector
objects.
Output
Method Overriding
Overriding a method in a superclass allows a subclass to change how that method is implemented. This means that the subclass implementation of the method will be used whenever the method is invoked on an instance of the subclass rather than the superclass implementation.
Code:
class Animal:
def make_sound(self):
print("Some generic animal sound.")
class Dog(Animal):
def make_sound(self):
print("Bark bark!")
class Cat(Animal):
def make_sound(self):
print("Meow meow!")
dog = Dog()
cat = Cat()
dog.make_sound() # Outputs: "Bark bark!"
cat.make_sound() # Outputs: "Meow meow!"
Code language: Python (python)
In this example, the Animal
class has a make_sound()
method that prints a generic animal sound. The Dog
and Cat
classes are subclasses of Animal
and both have their own version of the make_sound()
method that prints a specific sound for each type of animal. When the make_sound()
method is called on a “Dog” or “Cat” object, the subclass’s version of the method is executed, which overrides the superclass’s version. This is an instance of method overriding, in which a subclass provides an alternative to a method provided by its superclass.
Output
Conclusion
Polymorphism is a potent technique that simplifies and streamlines the development process. This blog post compared four distinct strategies for achieving polymorphism in Python. Which method of polymorphism implementation is optimal is context-specific. To ensure that the code is easily understood, scalable, and extendable while utilizing polymorphism, it is vital to bear in mind the concepts of maintainability and readability.
Frequently Asked Questions- (FAQs)
Is polymorphism implemented in different ways?
It’s true that there are several approaches to putting polymorphism into practice. Most often seen are duck typing, overloading methods and operators, and overriding methods.
Does polymorphism have different implementations?
Yes, polymorphism can be implemented in different ways based on the project requirements. There are four main ways to implement polymorphism in Python, which were discussed in this blog. Duck typing, method overloading, operator overloading, and method overriding are the four most common ways.
In what ways do polymorphisms differ from one another?
Polymorphisms differ from one another in terms of the type of data they take as parameters and the operation performed based on the type of data.
What are the different ways to implement polymorphism?
Duck typing, method overloading, operator overloading, and method overriding are the four main ways to use polymorphism in Python. Java offers two techniques to implement polymorphism: method overloading and method overriding. In Java, polymorphism can be broadly classified into two categories. Method overloading and method overriding are two ways to implement polymorphism at different stages of the program’s lifecycle.
Sharing is caring
Did you like what NIKESH JAGDISH MALIK wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses:
301 students learning
Haris
Python Crash Course for Beginners
Surendra varma Pericherla
Learn Data Structures Using Python