Sobes.tech
Junior — Middle

What is the role of the __iter__ method in implementing iterators in Python?

sobes.tech AI

Answer from AI

The __iter__ method in Python defines an object as iterable. It should return an iterator — an object that implements the __next__ method. This allows the object to be used in for loops and other constructs expecting an iterable.

Example:

class MyRange:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        self.current = 0
        return self

    def __next__(self):
        if self.current < self.n:
            val = self.current
            self.current += 1
            return val
        else:
            raise StopIteration

for i in MyRange(3):
    print(i)  # Will print 0, 1, 2

Here, __iter__ returns the object itself, which implements __next__. Thus, __iter__ is the entry point for creating an iterator from an object.