Sobes.tech
Junior — Middle

How should methods be implemented within a custom class to ensure its iterability?

sobes.tech AI

Answer from AI

To make a custom class iterable in Python, you need to implement the __iter__ method, which returns an iterator. An iterator is an object with a __next__ method that returns the next element or raises a StopIteration exception when there are no more elements.

A simple way is to make the class itself an iterator by implementing both methods:

class MyIterable:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        self.index = 0  # reset for a new iteration
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

Usage:

obj = MyIterable([1, 2, 3])
for item in obj:
    print(item)

Alternatively, __iter__ can return a separate iterator, for example, using a generator:

def __iter__(self):
    for item in self.data:
        yield item

This is a simpler and often preferred way.