PYTHON

OOPS: Polymorphism


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 
 

Overloading

We can use same operator or methods for different purposes. 

  •  + operator can be used for Arithmetic addition and String concatenation
print(10+20)#30
print('rohit'+'chuhamar') #rohitchuhamar
  •  * operator can be used for multiplication and string repetition purposes.
print(10*20) #200
print('rohit'*3) #rohitrohitrohit

 

Types of Overloading

  1. Operator Overloading
  2. Method Overloading
  3. Constructor Overloading

 

❑ Operator Overloading


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'
  • We can overload + operator to work with Book objects also.
  • For every operator Magic Methods are available. To overload any operator we have to override that Method in our class.
  • Internally + operator is implemented by using __add__() method..
  • This method is called magic method for + operator.
  • We have to override this method in our class.

List of operator and its magic method

operatorMagic method
+__add__
-__sub__
*__mul__
/__div__
//__floordiv__
%__mod__
**__pow__
+=__iadd__
-=__isub__
*=__imul__
/=__idiv__
//=__ifloordiv__
%=__imod__
**=__ipow__
<__lt__
<=__le__
>__gt__
>=__ge__
==__eq__
!=__ne__

 

❑ Method Overloading

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

Constructor overloading is not possible in Python. If we define multiple constructors then the last constructor will be considered. 

 

Method Overriding

  • Whatever members available in the parent class are by default available to the child class through inheritance. If the child class not satisfied with parent class implementation, then child class is allowed to redefine that method in the child class based on its requirement. This concept is called overriding.
  • Overriding concept applicable for both methods and constructors. 

 

 

 


PYTHON