Python, from Zero, for AILesson 63 of 89

Module 7 · Objects, generators and the shape a larger program takes

Dunder methods: making your own objects work with len, for, in and ==

In this lesson

  • 9 min read
  • 8 reading sections
  • Knowledge check
  • Lesson 4 of 10 in this chapter

This chapter’s goalRestructure a growing script into classes and dataclasses with a swappable provider behind one interface, implement the dunder methods that let your objects work with for, len, in and with, write a decorator that retries or caches, run a type checker and act on its output, make the project installable as a command with pyproject.toml, and profile it to say from measurement rather than guesswork where the time goes.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:40Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 10Free · no account needed
Lesson steps

Syntax is a method call

When you write len(x), Python calls x.__len__(). When you write for item in x, Python calls x.__iter__(). x == y is x.__eq__(y), x[3] is x.__getitem__(3), and x + y is x.__add__(y). The double-underscore names (“dunder”) are hooks that built-in syntax reaches for, and a class that implements them behaves like a built-in type.

You have used two already: __init__ and __repr__. Here are the ones that make a data-holding class pleasant to use, with the trap in each.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Dunder methods: making your own objects work with len, for, in and ==’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/dunder-methods (Accessed: 21 November 2026).