Skip to content

Lesson 09 · Python

Object-Oriented Design: Dunder Methods, Iterators & Generators

Teach your objects to work with len(), for loops and == by implementing dunder methods, then produce lazy sequences with the iterator protocol and generators.

45 minintermediateObject-Oriented Design

Prerequisites: Object-Oriented Design: Composition, Dataclasses & Properties

Learning objectives
By the end of this lesson, you will be able to:
  • Implement protocol methods like __len__, __getitem__ and __eq__ so objects work with built-ins
  • Explain the iterator protocol - __iter__, __next__, StopIteration - and how the for loop uses it
  • Write iterator classes by hand, managing their state honestly
  • Write generator functions and generator expressions for lazy sequences
  • Choose between lists and generators based on memory and reuse needs