Polymorphism is the ability of an object to take multiple forms. In the context of programming, polymorphism refers to the ability of an operator or method to perform differently depending on the number of parameters or the object in which an operator or a method is defined.
Python implements polymorphism by default for several operators and methods. You can also define custom methods that implement polymorphism using method overloading and method overriding.
In this tutorial, we’ll share examples of Python’s default operators and methods that implement polymorphism. Then, we’ll show you how to define custom methods that implement polymorphism.
Polymorphism in Default Python Operators and Functions
In this section, you will see a couple of examples of Python’s default operators and methods that support polymorphism.
Polymorphism in Default Operators
In case we haven’t said it enough already, Python contains some default operators that support polymorphism. We’re going to start with some simple examples that you may already be familiar with.
One example is the addition operator, “+”. When used between two or more integer operands, it returns the sum of the operands, as shown in the script below:
result = 10 + 20
print(result)
Output:
30
However, if you use the addition operator, “+”, between two strings, the result will be the concatenation of the two strings. Here’s an example.
result = "Mike" + " Dean"
print(result)
Output:
Mike Dean
Similarly, the negation operator, “-“, also supports polymorphism. For instance, it returns the difference between integers if the operands are integers, as shown in the following script.
result = 20 - 30
print(result)
Output:
-10
It can also return the difference between two sets if the operands are sets. Here’s an example.
set1 = set([10, 20, 30, 40])
set2 = set([20,40])
result = set1 - set2
print(result)
Output:
{10, 30}
From the examples above, you can see how a single operator performs different functions depending on the context and the operands.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
Polymorphism in Default Functions
Like operators, Python contains default functions that support Polymorphism. For instance, the range()
function returns an iterator containing a list of integers. Depending on the number of parameters passed, the range()
function returns different iterators. Let’s see a few examples.
In the script below, a single integer 10 is passed to the range()
function. This function returns an iterator from 0 to 9, i.e. 1 less than the integer passed as a parameter (10).
values = range(10)
for i in values:
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
If you pass two integers as parameter values, the range()
function returns an iterator that starts from the 1st integer parameter up to 1 less than the second parameter value.
Here’s how that looks:
values = range(5, 10)
for i in values:
print(i)
Output:
5
6
7
8
9
Finally, if you pass three integer parameters. The third parameter is considered as the step count. For example, the script below returns integer values starting from 5 up to 1 less than 10, with a step count of 2. Hence the resultant values are 5, 7, and 9.
values = range(5, 10, 2)
for i in values:
print(i)
Output:
5
7
9
The len()
function from Python also supports polymorphism. For example, if you pass a string value as a parameter to the len()
function, the function returns the number of characters in the input string.
result = len("hello-world")
print(result)
Output:
11
If you, however, pass a list to the len()
function, the result is the number of items in the list.
result = len(["name", "age", "gender"])
print(result)
Output:
3
Implementing Custom Polymorphism
Now that we understand the basics, we’re ready to define custom methods that support polymorphism via method overloading and method overriding.
Method overloading
Overloading a method refers to creating multiple methods with the same name but different numbers of parameters. Unlike C#, Java and other object oriented languages, in Python you do not create multiple methods with the same name for method overloading. Rather, you create a single method and then assign default values to some of the parameters.
Let’s define a method called return_product()
. You’ll be able to pass 2 or 3 parameter values to the method and the method will return the product of the passed parameter values.
def return_product(a, b, c = 1):
result = a * b * c
return result
From the above script, you can see that the third parameter “c” is assigned a default value of 1. If you pass 2 parameter values to the return_product()
method, a value of 1 will be used for the third parameter, “c”, and the method will essentially return the product of the first 2 parameter values passed in the method call. Look at the example below:
result = return_product(3,5)
print(result)
Output:
15
On the contrary, if you pass three parameters to the return_product()
method, the default value of 1 for the parameter “c” will be overriden, and hence the method will return the product of all three parameter values. Take a look:
result = return_product(3,5,5)
print(result)
Output:
75
Method Overriding
Method overriding occurs during class inheritance when a child class provides its own implementation of a method that exists with the same name in the parent class. Depending on the object (child or parent class), the method implementation of the parent or child is executed at runtime.
This sounds complicated so let’s explain it with an example. The script below defines three classes: display_name()
. The display_name()
, method. The display_name()
method.
class Item:
def display_name():
print("This is an item")
class Phone(Item):
def display_name():
print("This is a phone")
class Laptop(Item):
pass
Let’s create objects of the display_name()
method. The output shows that the object of the parent display_name()
method. While the child class display_name()
method, its object executes the display_name()
function inherited from the
Look at the full script below for reference. We included the class declarations above to make it easier to follow.
class Item:
def display_name():
print("This is an item")
class Phone(Item):
def display_name():
print("This is a phone")
class Laptop(Item):
pass
i = Item
p = Phone
l = Laptop
#calling method from parent class object
i.display_name()
#calling overriden method from the child class
p.display_name()
#calling method not overriden by the child class
l.display_name()
Output:
This is an item
This is a phone
This is an item
From the above output, you can see polymorphism in action when two child classes from the same parent class act differently even though the same method is called using objects of the two child classes.
I hope you enjoyed this tutorial on polymorphism in Python. For more Python examples and explanations, enter your email address in the form below:
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.