Sobes.tech
Junior — Middle

What functions need to be implemented to create your own iterator in a class?

sobes.tech AI

Answer from AI

To create a custom iterator in a Python class, you need to implement two methods:

  1. __iter__(self) — should return the iterator object. Usually, this is the object itself if it implements the __next__ method.
  2. __next__(self) — returns the next element in the sequence. When the sequence ends, it should raise a StopIteration exception.

Example implementation of an iterator in a class:

class MyRange:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        val = self.current
        self.current += 1
        return val

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

Thus, the class becomes an iterable object that can be used in for loops and other contexts expecting an iterator.