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(next(wi))
print(next(wi))
- __next__를 직접 구현 → next() 호출 시 한 단어씩 반환
- 끝에 다다르면 StopIteration 발생.
- 장점: 동작 원리를 확실히 볼 수 있음
- 단점: 코드가 장황하고 상태 관리(_idx)를 직접 해야 함
2. 제너레이터 기반 클래스 예제
class WordSplitGenerator:
def __init__(self, text):
self._text = text.split(' ')
def __iter__(self):
for word in self._text:
yield word # 제너레이터
def __repr__ (self):
return 'WordSplitGenerator(%s)' %(self._text)
wg = WordSplitGenerator('Do today what you could do tomorrow')
wt = iter(wg)
print(next(wt))
print(next(wt))
- __iter__ 안에서 yield 사용 → 자동으로 제너레이터 이터레이터 생성.
- StopIteration 처리를 직접 안 해도 됨.
- 상태(인덱스)도 내부적으로 자동 관리.
3. 두 방식 비교
| 구분 | WordSplitIter | WordSplitGenerator |
| 구현 방식 | __next__ 직접 작성 | yield로 간단하게 처리 |
| 상태 관리 | 인덱스 직접 관리 | 파이썬이 자동 관리 |
| 종료 처리 | StopIteration 직접 발생 | 자동으로 처리 |
| 코드 길이 | 증가 | 감소 |
정리하면
- WordSplitIter는 이터레이터 프로토콜을 직접 구현한 예제.
- WordSplitGenerator는 같은 동작을 제너레이터(yield) 로 더 간단하게 표현한 버전.
- 결과는 비슷하지만, 제너레이터가 훨씬 짧고 가독성 좋음.
이 두 가지를 비교해보면, 실무에서는 제너레이터 함수/표현식을 주로 쓰는 이유를 쉽게 이해할 수 있습니다.
'파이썬 > 기초 프로그래밍' 카테고리의 다른 글
| 파이썬 코루틴과 제너레이터 상태 & yield from 이해하기 (1) | 2025.09.09 |
|---|---|
| 파이썬 코루틴(제너레이터)로 메인↔서브 루틴 데이터 교환 이해하기 (0) | 2025.09.09 |
| 파이썬 이터레이터 예제: WordSplitIter (1) | 2025.09.08 |
| 파이썬 데코레이터와 클로저 정리 (0) | 2025.09.08 |
| 파이썬 클로저와 nonlocal — 언제 필요할까? (0) | 2025.09.08 |