나의 작은 valley
[Python] 이터레이터(Iterator) 본문
728x90
<이더레이터란>
my_list = ["사과", "딸기", "바나나"] 에서 lst는 컨테이너로서 사용된다.
for i in my_list: for 문에서 lst는 iterable 즉 반복 가능한 개체로서 사용된다.
print(i)
<for문 내부 관찰>
1) for문이 시작될 떄 lst의 __iter__()로 iterator를 생성
2) 내부적으로 i = __next__()
3) StopIteration 발생 시 종료
<3) 부과설명>
lst =["1","2","3"]
itr = iter(lst)
print("for 문 시작하기전 : " next(itr) )
for i in itr:
print(i)
# for문 시작하기전 : 1
# 2
# 3
<클래스로 이터레이터를 만드는 법>
class SquaredRange():
def __init__(self, begin, stop):
self.range = iter(range(begin, stop))
def __iter__(self):
return self #SquaredRange 자체가 이터레이터여서 self를 리턴
def __next__(self):
try:
value = next(self.range)
# 주의: value = next(self.range) * next(self.range)#를 사용한다면? 1*2,3*4가 됨.
return value * value
except StopIteration:
raise StopIteration
for i in SquaredRange(1, 5):
# i가 이미 제곱이기 때문에 squared = i * i 불필요!
print(i, end = " ")
디버거를 찍어보면 알겠지만 처음에 SquaredRange가 실행될 떄 ( i = 1일 떄)__init__, __iter__에 들어가는 데 이후부터는 바로 __next__로 간다.
728x90
'Computer Science > [Python] 문법 정리' 카테고리의 다른 글
[Python] 제너레이터 기반 코루틴(coroutine) (0) | 2022.08.23 |
---|---|
[Python] 재너레이터(Generator) (0) | 2022.08.23 |
[Python] 명령줄 인수 (0) | 2022.08.20 |
[Python] 멀티프로세스(Multi-Process) (0) | 2022.08.19 |
[Python] 멀티 스레드(multi thread) (0) | 2022.08.19 |
Comments