Polymorphism in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

#Polymorphism in python
#Method Overloading and Operator overloading
class Test:
    def addition(self,a=0,b=0,c=0,d=0):
        return a+b+c+d
   
#calling
T1=Test()
print(T1.addition(10,20,30,40))
print(T1.addition(10,20,30))
print(T1.addition(10,20))
print(T1.addition(10))
print(T1.addition())

Program 2

# Operator overloading
# a="Hello"
# b="Indore"
# print(type(a))
# print(type(b))
# print(a+b)

class MyClass:
    def __init__(self,n):
        self.n=n
    def __add__(self,other):
        return(self.n+other.n)  
    
    def __sub__(self,other):
        return(self.n-other.n)  
    def __mul__(self,other):
        return(self.n*other.n)  
    
    def __gt__(self,other):
        if(self.n>other.n):
            return True
        else:
            return False

    def __ge__(self,other):
        if(self.n>=other.n):
            return True
        else:
            return False

    def __lt__(self,other):
        if(self.n<other.n):
            return True
        else:
            return False

    def __le__(self,other):
        if(self.n<=other.n):
            return True
        else:
            return False
    def __eq__(self,other):
        if(self.n==other.n):
            return True
        else:
            return False



x=int(input("Enter First No"))
y=int(input("Enter Second No"))
M1=MyClass(x)
M2=MyClass(y)
print("M1>M2",M1>M2)       # M1.__gt__(self,other)
print("M1>=M2",M1>=M2)     # M1.__ge__(self,other)

print("M1<M2",M1<M2)       # M1.__lt__(self,other)
print("M1<=M2",M1<=M2)     # M1.__le__(self,other)
print("M1==M2",M1==M2)     # M1.__eq__(self,other)


# print(type(M1))
# print(type(M2))
# print("Addition=",M1+M2)                 # M1.__add__(self,other)

# print("Subtraction=",M1-M2)                 # M1.__sub__(self,other)

# print("Multiplication=",M1*M2)              # M1.__mul__(self,other)

 

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *