Poly means many. Morphs means forms.
Polymorphism means 'Many Forms’.
Lets Understand it By some examples:
you are the best example of polymorphism. In front of Your parents You will have one type of behavior and with friends another type of behavior. Same person but different behaviors at different places, which is nothing but polymorphism
We can use same operator or methods for different purposes.
print(10+20)#30
print('rohit'+'chuhamar') #rohitchuhamar
print(10*20) #200
print('rohit'*3) #rohitrohitrohit
We can use the same operator for multiple purposes, which is nothing but operator overloading.
class Book:
def __init__(self,pages):
self.pages=pages
b1=Book(100)
b2=Book(200)
print(b1+b2)
output:
TypeError: unsupported operand
type(s) for +: 'Book' and 'Book'
operator | Magic method |
---|---|
+ | __add__ |
- | __sub__ |
* | __mul__ |
/ | __div__ |
// | __floordiv__ |
% | __mod__ |
** | __pow__ |
+= | __iadd__ |
-= | __isub__ |
*= | __imul__ |
/= | __idiv__ |
//= | __ifloordiv__ |
%= | __imod__ |
**= | __ipow__ |
< | __lt__ |
<= | __le__ |
> | __gt__ |
>= | __ge__ |
== | __eq__ |
!= | __ne__ |
If 2 methods having same name but different type of arguments then those methods are said to be overloaded methods.
m1(int a)
m1(double d)
But in Python Method overloading is not possible. If we are trying to declare multiple methods with same name and different number of arguments then Python will always consider only last method.
Constructor overloading is not possible in Python. If we define multiple constructors then the last constructor will be considered.