Python program to compare two objects using operators

Here, we will see a Python program to compare two objects using a comparison operator.
Submitted by Shivang Yadav, on February 18, 2021

We have two objects in Python class TwoNum consisting of two values x and y. And then compare the two objects using a greater than operator which compares the addition of the values.

Class and its members used in the program

  • Class : TwoNum
    • Method : getValues() - get users input for the values of the class.
    • Method : putValues() - prints values of the class.
    • Method : __add__() [addition operator] - adds the values of two objects of the class.
    • Method : __gt__() [greater than operator] - compares the values of objects of the class and returns the true if first is greater than second.
    • Variable : x - stores an integer value.
    • Variable : y - stores an integer value

Program to illustrate comparison operator

class Twonum:
    def  getValues(self):
        self.__x=int(input("X = "))
        self.__y=int(input("Y = "))
    
    def PutValues(self):
        print(self.__x,self.__y)
    
    def  __gt__(self, T):
         if(self.__x+self.__y)>(T.__x+T.__y):
             return True
         else:
             return False

T1=Twonum()
T2=Twonum()

print("Enter values of object 1 : ")
T1.getValues()

print("Enter values of object 2 : ")
T2.getValues()

print("Object 1 : ")
T1.PutValues()

print("Object 2 : ")
T2.PutValues()

if(T1>T2):
    print("Yes Object 1 is Greater")
else:
    print("Object 1 Less Then or equals to Object 2")

Output:

Enter values of object 1 : 
X = 4
Y = 6
Enter values of object 2 : 
X = 2
Y = 6
Object 1 : 
4 6
Object 2 : 
2 6
Yes Object 1 is Greater

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.