Python program to Overload operators +, – and >=

 

Python program to Overload operators +, – and >=

Write a class Money with attributes Rupees and Paise. Overload operators + (addition of objects), – (subtraction of objects), and >=(comparing objects) so that they may be used on two objects. Also write functions so that a desired amount of money can be either added, subtracted from Money.

Video Tutorial

Source Code to Overload operators +, – and >= in Python

class Money:
    def __init__(self):
        self.R = 0
        self.P = 0
        
    def setValue(self, R, P):
        self.R = R
        self.P = P
        
    def __add__(self, M):
        Temp = Money()
        Temp.R = self.R + M.R
        Temp.P = self.P + M.P
        
        if (Temp.P>=100):
            Temp.P = Temp.P - 100
            Temp.R = Temp.R + 1
            
        return Temp
    
    def __sub__(self, M):
        Temp = Money()
        Temp.R = self.R - M.R
        Temp.P = self.P - M.P
        
        if (Temp.P<0):
            Temp.P = Temp.P + 100
            Temp.R = Temp.R - 1
            
        return Temp
    
    def __ge__(self, M):
        if (self.R > M.R or (self.R == M.R and self.P > M.P)):
            return 1
        else:
            return 0
        
    def display(self):
        print ("Rs.", self.R, "Paisa", self.P)
        
m1 = Money()
m2 = Money()
m3 = Money()

m1.setValue(15, 50)
m1.display()

m2.setValue(10, 60)
m2.display()

m3 = m1 + m2
m3.display()

m3 = m1 - m2
m3.display()

if(m1>=m2):
    print ('M1')
else:
    print("M2")

Output:

Case 1:

Rs. 15 Paisa 50

Rs. 10 Paisa 60

Rs. 26 Paisa 10

Rs. 4 Paisa 90

M1

Summary:

This tutorial discusses how to write a Python program to Overload operators +, – and >=. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

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

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds