Python Polymorphism


Write a program to check the object type
to know whether the method exists in the object or not.
polymorphism duck typing philosophy of python
1. python's type system is strong because every variable or object has a type that we can check with the type() function
2. python's type system is dynamic since the type of a variable is not
explicitly declared, but is changes with the content being stored object type is distinguish at the run time is called duck typing


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)



Write a program to overload the addition operator (+) to make it act on the class objects.
polymorphism
operator overloading
+ object__add__(self,other)
- object__sub__(self,other)
* object__mul__(self,other)
/ object__div__(self,other)
% object__mod__(self,other)
> object__gt__(self,other)
< object__lt__(self,other)



class Rupees:
    def __init__(self,r):
        self.r=r
    def __add__(self,other):
        rtop=self.r*100
        return rtop+other.p

class Paise:
    def __init__(self,p):
        self.p=p


r1=Rupees(5)
p1=Paise(50)

print("Total amount is ", r1+p1 ,"paise" )



Write a program to show method overloading to find sum of two or three numbers.


class methodoverdemo:
    def add(self,a=None,b=None,c=None):
        if(a!=None and b!=None and c!=None):
            print("Addition is",a+b+c)
        elif(a!=None and b!=None):
            print("Addition is",a+b)
        else:
            print("Enter two or three arguments")
         
m1=methodoverdemo()
m1.add(5,10,15)
m2=methodoverdemo()
m2.add(20,25)
m3=methodoverdemo()
m3.add(12.5,4.4)


Write a program to override the super class method in subclass.


class class1:
    def show(self):
        print("Method of class1")

class class2(class1):
    def show(self):
        print("Method of class 2")

obj1=class1()
obj2=class2()

obj1.show()
obj2.show()