파이썬에서 이터레이터 구현 방법
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
개발 툴
대상자
- Python 개발자, 특히 이터레이터/제너레이터 개념을 학습 중인 초보자
- 중급 난이도:
__iter__()
,__next__()
메서드 구현,yield
사용법 이해 필요
핵심 요약
- 이터레이터 구현 시
__iter__()
와__next__()
메서드 필수 __next__()
메서드 내yield
사용 시 제너레이터로 동작 가능__iter__()
는 이터레이터 객체 반환 또는yield
를 포함한 제너레이터 함수로 구현 가능
섹션별 세부 요약
1. 클래스 기반 이터레이터 구현
__iter__()
메서드는 이터레이터 객체 자체를 반환__next__()
메서드는 다음 요소를 반환하며StopIteration
예외 처리 필요- 예시 코드:
```python
class Cls:
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
return self.data[self.index]
raise StopIteration
```
2. 제너레이터 기반 이터레이터
__next__()
메서드 내yield
사용 시 제너레이터로 동작next()
함수 사용 시RuntimeError
발생 가능 (예:StopIteration
예외 처리 누락 시)- 예시 코드:
```python
class Cls:
def __next__(self):
if self.index < len(self.data):
yield self.data[self.index]
raise StopIteration
```
3. `__iter__()` 메서드의 특수한 경우
__iter__()
가yield
를 포함한 제너레이터 함수로 구현 시,iter()
함수 사용 가능- 예시 코드:
```python
class Cls:
def __iter__(self):
yield from ['a', 'b', 'c']
```
4. `__iter__()` 메서드의 오류 처리
__iter__()
가 이터레이터가 아닌 객체를 반환 시TypeError
발생- 예시:
return 'Hello'
로 구현 시iter()
호출 시 예외 발생
결론
- 이터레이터 구현 시
__iter__()
와__next__()
메서드를 반드시 구현하고, 제너레이터(yield
) 사용 시StopIteration
예외 처리를 철저히 해야 함 yield
사용 시next()
함수 대신__next__()
메서드를 호출하는 것이 안정적임__iter__()
메서드는 이터레이터 객체를 반환해야 하며, 제너레이터로 구현 시yield from
구문 활용 권장