DEV Community

kster
kster

Posted on • Updated on

Python Polymorphism

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.

Polymorphism in additional operator.

For integer data types, + operator is used to perform arithmetic addition operation

num1 = 1 
num2 = 2
print(num1+num2) # this program outputs '3'
Enter fullscreen mode Exit fullscreen mode

For string data types, + operator is used to perform concatenation

string1 = "Good"
string2 = "Morning"
print(string1+string2) # this prints 'Good Morning'
Enter fullscreen mode Exit fullscreen mode

We can see that a single operator + has been used to carry out different operations from distinct data types.

Function Polymorphism

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
Enter fullscreen mode Exit fullscreen mode

Class and Method Polymorphism

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"

Enter fullscreen mode Exit fullscreen mode

Here we created 2 classes. Pig and 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.

Top comments (0)