core Estimated learning time: 4 h

2.9 Magic methods and operator overloading

Your objects behave like built-ins where it helps.

Before:00. Orientation & SetupUnlocks:03. Data Handling & Analysis04. Classical AI — Agents, Search & Knowledge Representation

Magic methods plug your objects into Python's own syntax — len of x, equality, iteration — and implementing repr and eq well makes debugging and testing dramatically nicer. It sits in the object-oriented run as the layer that makes classes feel native. The subtle trap is defining equality without thinking about hashing; objects that compare equal but hash differently silently misbehave in sets and dict keys, and the failure appears far from its cause.

Work through these

  • __repr__, __str__, __eq__, __hash__

    The methods controlling how an object is displayed, compared for equality, and used as a dictionary key. Equality and hashing must agree, and this item explains why.

  • __len__, __getitem__, __iter__

    The methods that make an object behave like a collection: length, indexing and iteration. Implementing these lets your own types work with the language's built-in constructs.

  • __enter__/__exit__ for context managers

    The pair of methods behind the resource-handling construct, which lets your own objects clean up after themselves. It is a small amount of code for a large gain in safety.

  • __call__ and callable objects

    Making an object callable like a function, which is how many library components are designed. It blurs a distinction that turns out not to matter much in Python.

Sign in to keep your progress.

Free resources

Links last checked 29 Aug 2026.

Stuck here?

Ask a mentor. A real person answers, and they can see exactly which topic you're on. Usually within a couple of working days.

Checking your session…

Topics shown in module order.