Polymorphism is the condition of occurrence in different forms. Polymorphism refers to a single entity (method, operator, or object) to represent different types of scenarios. You probably already met with polymorphism without realizing it when you used the addition and len() functions. The '+' operator or addition can be used to add two integers or two floats or strings as seen in Example 1.
Example 1 Add two integers 10, and 20, float numbers 5.5 and 3.8, and two strings "This and " and "that.".
Solution:
Example 1 Create a string, list, dictionary, and tuple, and then apply the len function to each variable to determine the length of the data type.
Solution
Example 1 Add two integers 10, and 20, float numbers 5.5 and 3.8, and two strings "This and " and "that.".
Solution:
x = 10; y = 20Output
x1 = 5.5; y1 = 3.8
x2 = "This and "; y2 = "that."
res2 = x2 + y2
res = x+y
res1 = x1 + y1
print("{} + {} = {}".format(x,y,res))
print("{} + {} = {}".format(x1,y1,res1)
print("{} + {} = {}".format(x2,y2,res2))
10 + 20 = 30The point of this example is that the addition function (+) was used for adding two integers, two floats, and two strings. In general, the single operator was used in different operations for distinct data types. A good example of function polymorphism is the use of the len() function.
5.5 + 3.8 = 9.3
"This and " + "that." = "This and that."
Example 1 Create a string, list, dictionary, and tuple, and then apply the len function to each variable to determine the length of the data type.
Solution
var1 = "This is a string."
var2 =[3,5,6,3]
var3 = {"Car": "Mustang", "Color": "Black"}
var4 = (3,4,7,8)
print("len(var1) = {}".format(len(var1))
print("len(var2) = {}".format(var2))
print("len(var3) = {}".format(var3))
print("var4 = {}".format(var4))
var1 = 17From Example 2 it can be seen that len() function can be applied to many data types (strings, lists, dictionaries, and tuples). However, the return of the function len() has a different meaning in each case. In the case of a string, the len function will return the length of the string. In the case of lists, it will return the number of items in the list, and the same is in the case of tuples. In the case of dict, it will return the number of keys in the dictionary.
var2 = 4
var3 = 2
var4 = 4