Sobes.tech
Junior — Middle

What functions need to be overridden to implement your own iterator?.

sobes.tech AI

Answer from AI

To implement a custom iterator in Python, you need to define a class that implements two methods:

  1. __iter__(self) — should return the iterator object itself (usually self).
  2. __next__(self) — returns the next item in the sequence. If there are no more items, it should raise a StopIteration exception.

Here's an example of a simple iterator that returns numbers from 1 to 3:

class MyIterator:
    def __init__(self):
        self.current = 1
        self.max = 3

    def __iter__(self):
        return self

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

# Usage:
for num in MyIterator():
    print(num)

Thus, to create an iterator, it is enough to implement these two methods.