Polymorphism

 

Introduction to polymorphism

Polymorphism means to take more than one form. Poly means many and morphos means forms. A variable may store different types of data and the method may behave differently. This type of behaviour is called polymorphism.

Example:

a=5

b=10

c=a+b

print("c val is" ,c)


a1='abc'

b1='def'

c1=a1+b1

print("c val is" ,c1)

Output:

c val is 15

c val is abcdef


Duck typing philosophy of python

In python the data type of variable is not explicitly declared but than also all variable has its data type.

X=5

Print(type(x))

<class ‘int’>

For datatype we can identify following concepts:

  1. Python data type is strong because every variable has data type that can be identify with use of type function.

  2. Python data type is dynamic, because the data type is not declared then also it changes according the value assigned to variable.

Here we have discussed for variable same applied for method. If we want to call a method, it is not checking the object type.

Object type is distinguished at the run time is called duck typing.

Example:

class duck:

def speak(self):

print("Quack! Quack!")


class person:

def speak(self):

print("hello")


def call_speak(obj):

obj.speak()


o1=duck()

call_speak(o1)


o2=person()

call_speak(o2)

Output:

Quack! Quack!

Hello

The output of the above code suggest that the objects are identified at the run time. If the object belongs to duck class than duck class method invoked and if the object belongs to person class than person class speak method is called but if we have defined a class that does not have speak method and trying to call the speak method then AttributeError occurred. To overcome this problem we can use method called hasattr(). It is useful to identify that weather the class has the method or not. Following example describes it.

Example:

In following program hasattr method is used. It identifies whether the method or variable (attribute) is present or not.


class duck:

def speak(self):

print("Quack! Quack!")


class person:

def speak(self):

print("hello")


class dog:

def bark(self):

print("Bow bow")


def call_speak(obj):

if hasattr(obj,'speak'):

obj.speak()

elif hasattr(obj,'bark'):

obj.bark()

else:

print("Wrong object")


o1=duck()

call_speak(o1)


o2=person()

call_speak(o2)


o3=dog()

call_speak(o3)

Output:

Quack! Quack!

hello

Bow bow