Sobes.tech
Middle

Python'da iterator bo'lishi uchun ob'ektda nima bo'lishi kerak?

sobes.tech AI

AIdan javob

Python'da ob'ekt ikki usulni amalga oshirsa, u iterator bo'ladi:

  • __iter__() — o'zini o'zi qaytarishi kerak (odatda return self).
  • __next__() — ketma-ketlikning keyingi elementini qaytaradi va oxiriga yetganda StopIteration istisnosini chiqarishi kerak.

Oddiy iterator misoli:

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