Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Magic Methods and Operator Overloading
What will be the output of this code?
class Box:
    def __init__(self, volume):
        self.volume = volume
    def __lt__(self, other):
        return self.volume < other.volume

b1 = Box(10)
b2 = Box(20)
print(b1 < b2)
ANone
BTrue
CTypeError
DFalse
Step-by-Step Solution
Solution:
  1. Step 1: Understand __lt__ method behavior

    The __lt__ method compares the volume attributes of two Box objects using <.
  2. Step 2: Evaluate comparison

    b1.volume is 10 and b2.volume is 20, so 10 < 20 is True.
  3. Final Answer:

    True -> Option B
  4. Quick Check:

    __lt__ returns True if left volume is less [OK]
Quick Trick: __lt__ returns True if left is less than right [OK]
Common Mistakes:
  • Expecting False because 10 is less
  • Confusing __lt__ with __gt__
  • Thinking it raises an error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes