Sobes.tech
Middle

Ką turi turėti objektas, kad būtų iteratoriumi Python'e?

sobes.tech AI

Atsakymas iš AI

Objektas Python'e yra iteratorius, jei jis įgyvendina du metodus:

  • __iter__() — turi grąžinti patį iteratorių (paprastai return self).
  • __next__() — grąžina kitą sekos elementą ir pasiekus pabaigą turi išmesti išimtį StopIteration.

Pavyzdys paprasto iteratoriaus:

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)  # Išves 1, 2, 3