proomt

Search

Search posts, papers, and topics

All posts

Lerner Consulting BlogReuven Lerner1 min readintermediate

Python += calls __add__ and rebinds to a new object

Summary

A short blog post showing that Python's `+=` operator invokes `__add__` and rebinds the left‑hand variable to a new object rather than mutating it in place.

  • When a class defines `__add__`, the `+=` operator will call that method.
  • The result of `__add__` is assigned back to the left‑hand variable, so the variable now points to a new instance.
  • This behavior is demonstrated with a minimal `MyClass` that prints when `__add__` runs.

Understanding that `+=` may not be in‑place is important for writing correct mutable/immutable semantics and avoiding subtle bugs in Python code.

3/10

Related reading

  1. Quiz: Thinking Recursively in Python

    This is an interactive quiz from Real Python designed to test understanding of recursive thinking in Python. It covers identifying recursive structures, writing base and recursive cases, managing state, and using caching to avoid recomputation.

    Real Pythonrealpython.com1 min