Polymorphism is from the greek roots "poly" (many) and "morphe" (form).
In the context of programming, Polymorphism means that a single type entity (method, operator, or object) can behave in multiple ways.
For integer data types,
+ operator is used to perform arithmetic addition operation
num1 = 1 num2 = 2 print(num1+num2) # this program outputs '3'
For string data types,
+ operator is used to perform concatenation
string1 = "Good" string2 = "Morning" print(string1+string2) # this prints 'Good Morning'
We can see that a single operator
+ has been used to carry out different operations from distinct data types.
There are some functions in Python which are compatible to run multiple data types.
One of Python's built-in functions is
len(), it returns the length of an object
string = "python" print(len(string)) # this prints 6 list =[1,2,3,4] print(len(list))# this prints 4
class Pig: def diet(self): print("Pigs are omnivors") class Rabbit: def diet(self): print("Rabbits are herbivors") obj_pig = Pig() obj_rabbit = Rabbit() obj_pig.diet() #Returns "Pigs are omnivors" obj_rabbit.diet() #Returns "Rabbits are herbivors"
Here we created 2 classes.
Rabbit. Although both classes use the same method name
diet, they define those methods differently and wont interact. Objects instantiated from the class will use the method defined in that class.