SyntaxStudy
Sign Up
Python Intermediate 4 min read

Custom Iterable Classes

Custom Iterable Classes

Make any class iterable by implementing __iter__. Return a new iterator object (or self if the class is also an iterator).

Example
class EvenNumbers:
    def __init__(self, limit):
        self.limit = limit
    def __iter__(self):
        return (x for x in range(0, self.limit+1, 2))

for n in EvenNumbers(10):
    print(n, end=" ")
# 0 2 4 6 8 10
Pro Tip

Returning a generator from __iter__ is clean when you do not need manual state.