Fix the Broken __iadd__
Intermediate · Fix the bug · from Python Operator Overloading: Make Classes Work with +, -, ==
From the lesson: Python Operator Overloading: Make Classes Work with +, -, ==
The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.
Read the lessonThis Score class uses __iadd__ but the variable becomes None after +=. Find and fix the bug.
class Score:
def __init__(self, points=0):
self.points = points
def __iadd__(self, value):
self.points += value
# Bug: something is missing!
def __repr__(self):
return f'Score({self.points})'
s = Score(10)
s += 5
print(s)
More Operator Overloading exercises
- Add Two Points TogetherBeginner
- Scale a Vector with MultiplicationIntermediate
- Predict the Operator OutputIntermediate
- Build a Fraction ClassAdvanced
- Refactor Methods to OperatorsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz