Nearby lessons
91 of 108Python - Polymorphism
Detailed Tutorial Notes
PolymorphismPoly means many. Morphs means forms.
Polymorphism means 'Many Forms'.
Eg1: Yourself is best example of polymorphism.In front of Your parents You will have one type of
behaviour and with friends another type of behaviour.Same person but different behaviours at
different places,which is nothing but polymorphism.
Eg2: + operator acts as concatenation and arithmetic addition
Eg3: * operator acts as multiplication and repetition operator
Eg4: The Same method with different implementations in Parent class and childclasses.(overriding)
Related to polymorphism the following 4 topics are important
- Duck Typing Philosophy of Python
- Overloading
- Operator Overloading
- Method Overloading
- Constructor Overloading
- Overriding
- Method overriding
- constructor overriding
- Duck Typing Philosophy of Python: In Python we cannot specify the type explicitly. Based on provided value at runtime the type will be considered automatically. Hence Python is considered as Dynamically Typed Programming Language.
def f1(obj):obj.talk()
What is the type of obj? We cannot decide at the beginning. At runtime we can pass any type.Then
how we can decide the type?
At runtime if 'it walks like a duck and talks like a duck,it must be duck'. Python follows this
principle. This is called Duck Typing Philosophy of Python.
Demo Program:
1) class Duck:
2) def talk(self):
3) print('Quack.. Quack..')4)
5) class Dog:
6) def talk(self):
7) print('Bow Bow..')8)
9) class Cat:
10) def talk(self):
11) print('Moew Moew ..')12)
13) class Goat:
14) def talk(self):
15) print('Myaah Myaah ..')16)
17) def f1(obj):
18) obj.talk()19)
main.py
class Duck:
def talk(self):
print('Quack.. Quack..')Quack.. Quack..
Moew Moew ..
Bow Bow..
Myaah Myaah ..
The problem in this approach is if obj does not contain talk() method then we will get
AttributeError
Eg:
4)
5) class Dog:
6) def bark(self):
7) print('Bow Bow..')
8) def f1(obj):
9) obj.talk()10)
11) d=Duck()
12) f1(d)13)
main.py
class Duck:
def talk(self):
print('Quack.. Quack..')D:\durga_classes>py test.py
Quack.. Quack..
Traceback (most recent call last):
File "test.py", line 22, in
f1(d)
File "test.py", line 13, in f1
obj.talk()
AttributeError: 'Dog' object has no attribute 'talk'
But we can solve this problem by using hasattr() function.
hasattr(obj,'attributename')
attributename can be method name or variable name
Demo Program with hasattr() function:
4)
5) class Human:
6) def talk(self):
7) print('Hello Hi...')8)
9) class Dog:
10) def bark(self):
11) print('Bow Bow..')12)
13) def f1(obj):
14) if hasattr(obj,'talk'):
15) obj.talk()
16) elif hasattr(obj,'bark'):
17) obj.bark()18)
19) d=Duck()
20) f1(d)21)
22) h=Human()
23) f1(h)24)
25) d=Dog()
26) f1(d)
27) Myaah Myaah Myaah...Overloading:
We can use same operator or methods for different purposes.
Eg1: + operator can be used for Arithmetic addition and String concatenation
print(10+20)#30
print('durga'+'soft')#durgasoftEg2: * operator can be used for multiplication and string repetition purposes.
print(10*20)#200
print('durga'*3)#durgadurgadurgaEg3: We can use deposit() method to deposit cash or cheque or dd
deposit(cash)
deposit(cheque)
deposit(dd)
There are 3 types of overloading
- Operator Overloading
- Method Overloading
- Constructor Overloading
- Operator Overloading: We can use the same operator for multiple purposes, which is nothing but operator overloading. Python supports operator overloading. Eg1: + operator can be used for Arithmetic addition and String concatenation
print(10+20)#30
print('durga'+'soft')#durgasoftEg2: * operator can be used for multiplication and string repetition purposes.
print(10*20)#200
print('durga'*3)#durgadurgadurga
Demo program to use + operator for our class objects:
1) class Book:
2) def __init__(self,pages):
3) self.pages=pages4)
5) b1=Book(100)
6) b2=Book(200)
7) print(b1+b2)D:\durga_classes>py test.py
Traceback (most recent call last):
File "test.py", line 7, in
print(b1+b2)
TypeError: unsupported operand type(s) for +: 'Book' and 'Book'We can overload + operator to work with Book objects also. i.e Python supports Operator
Overloading.
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.
Demo program to overload + operator for our Book class objects:
1) class Book:
2) def __init__(self,pages):
3) self.pages=pages4)
5) def __add__(self,other):
6) return self.pages+other.pages7)
main.py
Overloading > and <= operators for Student class objects: class Student: def __init__(self,name,marks): self.name=name self.marks=marks def __gt__(self,other): return self.marks>other.marks def __le__(self,other): return self.marks<=other.marks
The following is the list of operators and corresponding magic methods.
+ ---> object.__add__(self,other)
- ---> object.__sub__(self,other)
- ---> object.__mul__(self,other) / ---> object.__div__(self,other) // ---> object.__floordiv__(self,other) % ---> object.__mod__(self,other)
- * ---> object.__pow__(self,other) += ---> object.__iadd__(self,other)
- = ---> object.__isub__(self,other)
- = ---> object.__imul__(self,other) /= ---> object.__idiv__(self,other) //= ---> object.__ifloordiv__(self,other) %= ---> object.__imod__(self,other)
- *= ---> object.__ipow__(self,other) < ---> object.__lt__(self,other) <= ---> object.__le__(self,other) > ---> object.__gt__(self,other) >= ---> object.__ge__(self,other) == ---> object.__eq__(self,other) != ---> object.__ne__(self,other)
9)
10)
main.py
class Employee: def __init__(self,name,salary): self.name=name self.salary=salary def __mul__(self,other): return self.salary*other.days
10>20 = False
s1>s2= False
s1 s1<=s2= True s1>=s2= FalseProgram to overload multiplication operator to work on Employee objects:
7)
8) class TimeSheet:
9) def __init__(self,name,days):
10) self.name=name
11) self.days=days12)
main.py
This Month Salary: 12500