Sobes.tech
Middle

Ko vajadzētu būt objektam, lai tas būtu iterators Python?

sobes.tech AI

Atbilde no AI

Objekts Python valodā ir iterators, ja tas īsteno divas metodes:

  • __iter__() — tam jāatgriež pats iterators (parasti return self).
  • __next__() — atgriež nākamo secības elementu, un, sasniedzot beigas, jāizmet izņēmums StopIteration.

Vienkārša iteratora piemērs:

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)  # Izvadīs 1, 2, 3