Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Iterator Function ใน Python: __iter__ และ __next__


Iterator protocol ใน Python ประกอบด้วย 2 เมธอด:

  • __iter__(): เรียกตอน initialize iterator คืน object ที่มี __next__()
  • __next__(): คืนอิลิเมนต์ถัดไป หากหมด raise StopIteration

ตัวอย่าง: Custom Iterator ยกกำลัง 2

class Pow_of_Two:
    def __init__(self, max=0):
        self.max = max
    def __iter__(self):
        self.n = 0
        return self
    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration("Message")

a = Pow_of_Two(4)
i = iter(a)
print(next(i))  # 1
print(next(i))  # 2
print(next(i))  # 4
print(next(i))  # 8
print(next(i))  # 16
print(next(i))  # StopIteration

ผลลัพธ์

1
2
4
8
16
StopIteration error will be raised