Sobes.tech
Junior — Middle

Can you explain what the __iter__ method does in the context of Python iterators?

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.

When you use a for loop or the list() function on an object, Python calls its __iter__ to get an iterator, and then repeatedly calls __next__ to get the elements.

Example:

class CountUpTo:
    def __init__(self, max):
        self.max = max
    def __iter__(self):
        self.current = 1
        return self
    def __next__(self):
        if self.current <= self.max:
            val = self.current
            self.current += 1
            return val
        else:
            raise StopIteration

for num in CountUpTo(3):
    print(num)

This code will output numbers from 1 to 3.