Sobes.tech
Middle

Cosa deve avere un oggetto per essere un iteratore in Python?

sobes.tech AI

Risposta dell'AI

Un oggetto è un iteratore in Python se implementa due metodi:

  • __iter__() — deve restituire se stesso (di solito return self).
  • __next__() — restituisce il prossimo elemento della sequenza e deve sollevare un'eccezione StopIteration quando si raggiunge la fine.

Esempio di un semplice iteratore:

class CountUpTo:
    def __init__(self, max):
        self.max = max
        self.current = 0

    def __iter__(self):
        return self

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

counter = CountUpTo(3)
for num in counter:
    print(num)  # Stampa 1, 2, 3