Q:

Python program to compare two objects using operators

belongs to collection: Python class & object programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to illustrate the working of list o... >>
<< Python program to illustrate Matrix Addition using...