Sobes.tech
Middle

Čo musí mať objekt, aby bol v Pythone iterátor?

sobes.tech AI

Odpoveď od AI

Objekt je v Pythone iterátor, ak implementuje dve metódy:

  • __iter__() — musí vrátiť sám seba (zvyčajne return self).
  • __next__() — vráti ďalší prvok sekvencie a pri dosiahnutí konca má vyhodiť výnimku StopIteration.

Príklad jednoduchého iterátora:

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)  # Vytlačí 1, 2, 3