Sobes.tech
Middle

Co musí mít objekt, aby byl v Pythonu iterátorem?

sobes.tech AI

Odpověď od AI

Objekt je v Pythonu iterátor, pokud implementuje dvě metody:

  • __iter__() — musí vracet sám sebe (obvykle return self).
  • __next__() — vrací další prvek sekvence a při dosažení konce vyvolá výjimku StopIteration.

Příklad jednoduchého iterátoru:

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