Bird
0
0

Given this class, how would you modify it to support chaining additions like a + b + c?

hard📝 Application Q8 of 15
Python - Magic Methods and Operator Overloading
Given this class, how would you modify it to support chaining additions like a + b + c?
class Box:
    def __init__(self, size):
        self.size = size
    def __add__(self, other):
        return Box(self.size + other.size)
ANo change needed; chaining works as is
BModify __add__ to return self instead of new Box
CAdd __radd__ method to support chaining
DChange __init__ to accept multiple sizes
Step-by-Step Solution
Solution:
  1. Step 1: Understand chaining with __add__

    Since __add__ returns a new Box instance, expressions like a + b + c call __add__ repeatedly on Box objects.
  2. Step 2: Confirm chaining behavior

    Each addition returns a Box, so chaining works without changes.
  3. Final Answer:

    No change needed; chaining works as is -> Option A
  4. Quick Check:

    Returning new Box enables chaining [OK]
Quick Trick: Return new instance to enable chaining [OK]
Common Mistakes:
  • Thinking __radd__ is needed for chaining
  • Returning self breaks chaining
  • Changing __init__ unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes