Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Support In-Place Addition with __iadd__

Implement in-place addition behavior for a mutable numeric wrapper using __iadd__.

Python practice25 minMagic Methods & Operator OverloadingAdvancedLast updated April 11, 2026

Problem statement

Create a small mutable numeric wrapper class MutableNumber that stores a numeric value. Implement the __iadd__ magic method so that the object supports in-place addition using the '+=' operator. The method should: - Mutate the receiver's stored value by adding the other operand's numeric value. - Support adding an int or float, or another MutableNumber instance. - Return self so chained in-place operations behave correctly. If the other operand type is unsupported, return NotImplemented.

Task

Learn to implement __iadd__ so objects can be updated with the '+=' operator and return themselves, handling different operand types correctly.

Examples

Basic in-place addition

Input

iadd_demo(2, 3)

Output

5

Creates MutableNumber(2), does += 3 (an int). The internal value becomes 5 and that value is returned by the helper function.

Input format

The test harness will call iadd_demo(a, b) where a is the initial numeric value and b is either a number (int/float) or a MutableNumber instance.

Output format

Return the numeric value stored inside the MutableNumber after performing the in-place addition.

Constraints

- You must implement __iadd__ on the MutableNumber class. - __iadd__ should mutate self.value and return self. - If the other operand is a MutableNumber, use its .value. - For unsupported types, return NotImplemented.

Samples

Sample 1

Input

iadd_demo(10, MutableNumber(5))

Output

15

Adding another MutableNumber adds its value.