Bird
0
0

What will be the output of this code?

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

num1 = Number(5)
num2 = Number(10)
print(num1 + num2)
A510
BTypeError
C15
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand the __add__ magic method

    The __add__ method defines how the + operator works for Number objects by adding their 'value' attributes.
  2. Step 2: Calculate the addition

    num1.value is 5 and num2.value is 10, so 5 + 10 = 15.
  3. Final Answer:

    15 -> Option C
  4. Quick Check:

    __add__ adds values = 15 [OK]
Quick Trick: __add__ defines + behavior for objects [OK]
Common Mistakes:
  • Expecting string concatenation '510'
  • Thinking it causes a TypeError
  • Assuming it returns None

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes