1. 먼저, 원본 코드로 이해하기
class WordSplitIter:
def __init__(self, text):
self._idx = 0
self._text = text.split(' ')
def __next__(self):
print('Called __next__')
try:
word = self._text[self._idx]
except IndexError:
raise StopIteration('Stopped Iteration.')
self._idx += 1
return word
def __repr__(self):
return 'WordSplit(%s)' %(self._text)
wi = WordSplitIter('Do today what you could do tomorrow')
print(wi)
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
print(next(wi))
실행 흐름
- __init__ : 문자열을 공백 기준으로 잘라 리스트에 저장.
- __next__ : next()가 호출될 때마다 리스트에서 한 단어씩 꺼냄.
- 단어를 꺼내면 _idx를 하나 증가.
- 범위를 벗어나면 StopIteration 발생 → 순회 종료.
- __repr__ : 객체를 출력할 때 리스트 상태를 보여줌.
출력 예시
WordSplit(['Do', 'today', 'what', 'you', 'could', 'do', 'tomorrow'])
Called __next__
Do
Called __next__
today
Called __next__
what
Called __next__
you
Called __next__
could
Called __next__
do
Called __next__
tomorrow
Called __next__
Traceback (most recent call last):
...
StopIteration: Stopped Iteration.
- WordSplitIter는 사용자 정의 이터레이터 예제
- next()를 호출할 때마다 __next__가 실행되어 단어를 하나씩 반환.
- 마지막 단어까지 다 소비하면 StopIteration으로 종료.
파이썬의 이터레이터 동작 방식을 직접 눈으로 확인할 수 있는 간단한 예제입니다
'파이썬 > 기초 프로그래밍' 카테고리의 다른 글
| 파이썬 코루틴(제너레이터)로 메인↔서브 루틴 데이터 교환 이해하기 (0) | 2025.09.09 |
|---|---|
| 파이썬 이터레이터 vs 제너레이터 (0) | 2025.09.08 |
| 파이썬 데코레이터와 클로저 정리 (0) | 2025.09.08 |
| 파이썬 클로저와 nonlocal — 언제 필요할까? (0) | 2025.09.08 |
| 파이썬 클로저(Closure)와 nonlocal 키워드 (0) | 2025.09.08 |