Python หยุดการวนซ้ำ
StopIteration
เพื่อป้องกันไม่ให้การวนซ้ำเกิดขึ้นตลอดไป เราสามารถใช้
StopIteration
คำสั่งได้
ใน__next__()
เมธอดนี้ เราสามารถเพิ่มเงื่อนไขการสิ้นสุดเพื่อทำให้เกิดข้อผิดพลาด หากทำซ้ำตามจำนวนที่กำหนด:
ตัวอย่าง
หยุดหลังจากทำซ้ำ 20 ครั้ง:
class MyNumbers:
def __iter__(self):
self.a =
1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass =
MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)