Introduction:
polymorphism is one of the many concepts in object oriented programming. I have previously discussed in details about different parts of object oriented programming in this OOPs post. In this post, we will discuss about polymorphism.
Definition:
In object oriented programming using a function for many purposes is termed as polymorphism. Polymorphism is a way to use the same function name, while it operates differently based on different parameters and classes it occurs in. I will explain it with a small example now.
Example:
Look at the following code:
class examplesome:
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
def funct(self):
return self.a+self.b+self.c
class examplesum:
def __init__(self,a,b):
self.a = a
self.b = b
def funct(self):
return self.a+self.b
Observe here that examplesome and examplesum contains functions with same name. But application wise, they are abruptly different. This is an application of the polymorphism property. It is important to note that polymorphism is a common practice in not only python but among all the OOP programing languages.
Polymorphism is also observed in case of operators. For example consider that "+" operator returns a sum of two integers when the operands are integers, but returns the concatenated string when the operands are strings. This is normally called operator overloading. And this also comes under polymorphism.
For understanding similar other concepts like inheritance, encapsulations and others, read this OOPs post. Thanks for reading!
[PS: thanks to biswajit namasudra for pointing out operator overloading.]
Comments
Post a Comment