34
loading...
This website collects cookies to deliver better user experience
Poly - many
morphism -many forms
Polymorphism is the condition of occurrence in different forms.
+
operator is used to add two numbers as well as to coconcate two strings. In the same way, the product operator *
is used to multiply two integers, floating numbers as well as two complex numbers in Python. This is an example of polymorphism which we have unknowingly used until now.len()
function which takes in any iterable type. when string is passed, it returns the number of characters, when list is passed it returns the number of elements and when a dictionary is passed, it returns the number of key values.class ape():
food=""
def __init__(self,weight):
self.weight=weight
def cry(self):
pass # Do nothing
def eat(self):
print(self.food)
class chimpanzee(ape):
def __init__(self,weight):
super().__init__(weight)
self.food="bananas"
def cry(self):
print("I am a chimp")
class gorrilla(ape):
def __init__(self,weight):
super().__init__(weight)
self.food="fruits"
def cry(self):
print("I am a gorrilla")
a=chimpanzee(20)
b=chimpanzee(25)
c=gorrilla(50)
a.cry()
b.cry()
c.cry()
print(a.weight)
print(b.weight)
print(c.weight)
a.eat()
b.eat()
c.eat()
I am a chimp
I am a chimp
I am a gorrilla
20
25
50
bananas
bananas
fruits
Study the above example carefully. What we have seen above is an example of polymorphism itself!
a
is both a ape as well as a chimpanzee. So can we treat a as n ape? so can we treat a
, b
, c
as equal apes? We can using polymorphism. At times, we may need to consider that a,b,c
are just apes and not gorillas or chimpanzees and treat them all equally. This decreases the overhead of treating objects of different subclasses species as different entities. For example tomorrow if I want to add an Orangutan subclass, I will not require to go back and change everything I had written earlier. Using Polymorphism I can just treat them as equals. We overload the functions.class ape():
food=""
def __init__(self,weight):
self.weight=weight
def cry(self):
pass # Do nothing
def eat(self):
print(self.food)
class chimpanzee(ape):
def __init__(self,weight):
super().__init__(weight)
self.food="bananas"
def cry(self):
print("I am a chimp")
class gorrilla(ape):
def __init__(self,weight):
super().__init__(weight)
self.food="fruits"
def cry(self):
print("I am a gorrilla")
a=chimpanzee(20)
b=chimpanzee(25)
c=gorrilla(50)
for i in (a,b,c):
i.cry()
print(i.weight)
i.eat()