파이썬에는 컨테이너에 대한 반복 개념이 있습니다. 반복자에는 두 가지 고유한 기능이 있습니다. 이러한 함수를 사용하여 사용자 정의 클래스를 사용하여 반복을 지원할 수 있습니다. 이러한 함수는 __iter__()입니다. 그리고 __next__() .
메서드 __iter__()
__iter__() 메서드는 반복자 객체를 반환합니다. 한 클래스가 다른 유형의 반복을 지원하는 경우 다른 작업을 수행하기 위해 다른 메서드가 있을 수 있습니다.
메서드 __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