คำอธิบาย
Iterator เป็นอ็อบเจ็กต์ในไพ ธ อนที่ใช้โปรโตคอลการวนซ้ำ ทูเพิล, รายการ, ชุด เรียกว่า inbuilt iterators ใน Python มีเมธอดสองประเภทในโปรโตคอลการวนซ้ำ
__iter__() : เมธอดนี้ถูกเรียกเมื่อเราเริ่มต้นตัววนซ้ำและต้องส่งคืนอ็อบเจ็กต์ที่ประกอบด้วยเมธอด next() หรือ __next__()(ใน Python 3)
next() หรือ __next__() (ใน Python 3) : เมธอดนี้ควรส่งคืนองค์ประกอบถัดไปจากลำดับการวนซ้ำ เมื่อใช้ตัววนซ้ำกับลูป for ลูป for จะเรียก next() โดยตรงบนอ็อบเจ็กต์ iterator
โค้ดตัวอย่าง
# creating a custom iterator
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(i.__next__())
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i)) ผลลัพธ์
1 2 4 8 16 StopIteration error will be raised