Write a python program to comparison between two objects using the > operator


The python program defines a Number class that represents a number. It allows you to create Number objects, display them as strings, and perform a greater-than comparison using the > operator. Here's a breakdown of the code:

  • class Number: This class represents a number with an attribute value.
  • __init__(self, value): The constructor initializes a Number object with the provided value.
  • __str__(self): This special method returns a string representation of the number.
  • __gt__(self, other): This special method overloads the > (greater-than) operator, allowing you to compare two Number objects. It checks whether the value of the current object is greater than the value of the other object.
  • Two Number objects, number1 and number2, are created with different values.
  • The code compares number1 and number2 using the > operator in an expression and stores the result in the variable res.
  • Depending on the result, the code prints a message indicating whether number1 is greater than number2.

Here's what the code does:

  • It creates two Number objects with different values.
  • It compares the two numbers using the > operator.
  • It prints a message based on the result of the comparison.

Source Code

class Number:
    def __init__(self, value):
        self.value = value
 
    def __str__(self):
        return str(self.value)
 
    def __gt__(self, other):
        return self.value > other.value
 
# Create two Number objects
number1 = Number(5)
number2 = Number(3)
 
# Compare the two numbers using the > operator in an expression
res = number1 > number2
 
if res:
    print(number1, "is greater than", number2)
else:
    print(number1, "is not greater than", number2)

Output

5 is greater than 3

Example Programs