ใน python มีแนวคิดการวนซ้ำบนคอนเทนเนอร์ ตัววนซ้ำมีสองหน้าที่ที่แตกต่างกัน การใช้ฟังก์ชันเหล่านี้ เราสามารถใช้คลาสที่กำหนดโดยผู้ใช้เพื่อสนับสนุนการวนซ้ำ ฟังก์ชันเหล่านี้คือ __iter__() และ __next__() .
วิธีการ __iter__()
__iter__() วิธีการส่งกลับวัตถุ iterator หากคลาสหนึ่งรองรับการวนซ้ำประเภทต่างๆ ก็สามารถใช้เมธอดอื่นเพื่อทำงานอื่นได้
วิธีการ __next__()
__next__() วิธีการส่งกลับองค์ประกอบถัดไปจากคอนเทนเนอร์ เมื่อรายการเสร็จสิ้น มันจะเพิ่ม StopIteration ข้อยกเว้น
โค้ดตัวอย่าง
class PowerIter:
#It will return x ^ x where x is in range 1 to max
def __init__(self, max = 0):
self.max = max #Set the max limit of the iterator
def __iter__(self):
self.term = 0
return self
def __next__(self):
if self.term <= self.max:
element = self.term ** self.term
self.term += 1
return element
else:
raise StopIteration #When it exceeds the max, return exception
powIterObj = PowerIter(10)
powIter = iter(powIterObj)
for i in range(10):
print(next(powIter))
ผลลัพธ์
1 1 4 27 256 3125 46656 823543 16777216 387420489