Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Python - Magic Methods and Operator Overloading
What will be the output of the following code?
class Number:
    def __init__(self, value):
        self.value = value
    def __gt__(self, other):
        return self.value > other.value

n1 = Number(5)
n2 = Number(3)
print(n1 > n2)
AFalse
BTypeError
CTrue
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand the __gt__ method

    The __gt__ method compares self.value and other.value.
  2. Step 2: Evaluate the comparison

    n1.value is 5 and n2.value is 3, so 5 > 3 is True.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    5 > 3 = True [OK]
Quick Trick: Check the values inside objects when comparing [OK]
Common Mistakes:
  • Forgetting to compare attributes inside objects
  • Expecting print to show object addresses
  • Confusing __gt__ with __lt__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes