Sobes.tech
Middle

Co musi mieć obiekt, aby był iteratorem w Pythonie?

sobes.tech AI

Odpowiedź od AI

Obiekt jest iteratorem w Pythonie, jeśli implementuje dwie metody:

  • __iter__() — powinna zwracać sam iterator (zazwyczaj return self).
  • __next__() — zwraca następny element sekwencji, a na końcu powinna rzucić wyjątek StopIteration.

Przykład prostego iteratora:

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)  # Wypisze 1, 2, 3