Have you ever had a problem where you could not figure out why a specific function or method was failing? That is because Polymorphism, it is the key feature of Python that makes code more reliable and easier to understand. Furthermore, Polymorphism in Python is extremely important in software development, as it allows you to create reusable and adaptable code.
In this article, we will explore the basics of Polymorphism in Python and discuss how to use it in your code. We will also look at some common uses for Polymorphism and show you how to implement it in your projects. Let us get started.
Table of Contents
What is Polymorphism?
Polymorphism in Python is a coding technique with multiple versions of a function or variable within the same module, file, or script. This is useful for situations where you want two or more objects that are of the same type to act differently from one another. This offers flexibility and modularity within your codebase as you can write different versions of a particular function for different situations.
There are two types of Polymorphism
- Compile time Polymorphism
- Run-time Polymorphism
Polymorphism in Python: Advantages
- It enables you to write code in an object-oriented language without explicitly stating which type of object you are talking about.
- This reduces repetitive coding, makes your code easier to read, and makes debugging easier.
- It also helps with code reuse as different types of objects can be easily incorporated into existing scripts or programs.
Operator Polymorphism in Python
In programming languages, operators are used to perform any calculations. Operator Polymorphism is a phenomenon that occurs when different operators have different behavior based on the data they are working with.
In the below example, we have used the addition or plus operator to merge or join the two strings regardless of the addition of any number
Let us have a look on the code snippet:
str1 = 'my name ' str2 = 'is Faryal haider' print(str1 + str2)
Polymorphism with Classes and Methods
The polymorphic nature makes it easier to reuse classes and methods in Python. Remember that a class is like a blueprint, and an object is like a specific blueprint implementation. As a result, Polymorphic objects that instantiate a class will include code that is part of the class. Therefore, the methods of the existing class will be inherited by a new class created from an existing class.
Below code snippet example shows how we can use polymorphism in class:
class Toyota(): def Motor_corporation(self): print("Toyota Motor Corporation is a Japanese multinational automotive manufacturer") class Hyundai(): def Motor_corporation(self): print("Hyundai is a South Korean multinational automotive manufacturer")obj_T = Toyota() obj_H = Hyundai() for Vehicles in (obj_T, obj_H): Vehicles.Motor_corporation()
Polymorphism with a Built-in Function
Built-in function in python refers to a predefined set of functions. These functions are usually included as part of the standard library and can be accessed without having to import any particular module.
In the Below code snippet, we have to use the polymorphism concept by the built-in function of python. Let us have a look,
class Toyota(): def Motor_corporation(self): print("Toyota Motor Corporation is a Japanese multinational automotive manufacturer") class Hyundai(): def Motor_corporation(self): print("Hyundai is a South Korean multinational automotive manufacturer") def func(obj): obj.Motor_corporation() obj_T = Toyota() obj_H = Hyundai() func(obj_T) func(obj_H)
Polymorphism User-defined Function
The user-defined function in Python that allows you to define custom functions in your program. This can be helpful when you need to perform tasks that are not provided by built-in functions or when you want to customize the behaviour of an existing function
Consider the following code example to understand better how we can use polymorphism by defining our functions:
def add(a, b,): return a + b print(add(78, 56))
Polymorphism with Inheritance
Overriding methods extend the functionality of a class by adding your implementation of an inherited method (inheritance is a mechanism that allows classes to inherit properties and methods from other classes). This can be useful if you want to create a class that behaves similarly to an existing class without writing all of the code yourself.
Consider the following code example to understand Polymorphism in inheritance by the overriding method:
class South_Asia: def intro(self): print("South asia has 6 countries") def continent(self): print("south asia is a continent") class Pakistan(South_Asia): def country(self): print("Pakistan is a 33rd largest country in area") class India(South_Asia): def country(self): print("India is the 7th largest country in world in area") obj_SA = South_Asia() obj_Pak = Pakistan() obj_ind = India() obj_SA.intro() obj_SA.continent() obj_Pak.intro() obj_Pak.country() obj_ind.intro() obj_ind.country()
In Python, It has referred to as Overriding when the superclass and the child class have the same method signature (name and arguments). Method overriding is the ability of a class to override an inherited method with a new one. It is a runtime polymorphism.
# add 2 numbers print(100 + 200) # concatenate two strings print('Pak' + 'Ind') print([10, 20, 30] + ['Pak', 'ind', 'Austria'])
Why is polymorphism needed?
The term polymorphism is frequently used when discussing object-oriented Programming in Python. Objects in object-oriented programming must assume a wide range of forms. In software development, this property is essential. Because of polymorphism, the same action may be performed in various ways.
What is difference between compile time and run time polymorphism?
In Compile-time Polymorphism error will resolve by the compiler, also known as static binding.
In Runtime Polymorphism error will not resolve by the compiler, also known as Dynamic binding.
This article discussed the basics of Polymorphism in Python with code examples and how it can be used to write complex code into flexible code that is easy to modify. The next time you write a function or method with similar functionality but some customizations such as different argument values or return types, consider using Polymorphism instead. It will make your code flexible and easier to maintain in the long run. Thanks for reading.