사용자 정의 이터레이터

Python 중급 객체 지향 프로그래밍

Jake Roach

Data Engineer

이터레이터

객체 모음이나 데이터 스트림을 순회하며, 한 번에 하나의 항목을 반환하는 클래스

  • list, tuple과 유사하지만 동작은 다름
  • 탐색, 변환, 생성
  • for 루프로 순회
  • next() 함수

$$

이터레이터 프로토콜...

# 컬렉션
chuck = NameIterator("Charles Carmicheal")
for letter in chuck:
    print(letter)
C
h
u
...
# 데이터 스트림
fun_game = DiceGame(rolls=3)
next(fun_game)  # ... 계속
4
Python 중급 객체 지향 프로그래밍

이터레이터 프로토콜

__iter__()

  • 이터레이터를 반환(여기서는 자기 자신 참조)
  • ... return self

$$

__next__()

  • 컬렉션/데이터 스트림의 다음 값을 반환
  • 순회, 변환, 생성이 여기서 수행됨

$$

클래스가 이터레이터로 인정되려면 __iter__()__next__()를 모두 정의해야 합니다!

Python 중급 객체 지향 프로그래밍

이터레이터 예시

class CoinFlips:
    def __init__(self, number_of_flips):
        self.number_of_flips = number_of_flips  # 총 던지기 횟수 저장
        self.counter = 0

    def __iter__(self):
        return self  # 이터레이터 자신의 참조 반환

    # 다음 동전을 던지고 결과 반환
    def __next__(self):
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])
Python 중급 객체 지향 프로그래밍

예시 이터레이터 사용

three_flips = CoinFlips(3)

# 동전을 세 번 던지기
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Python 중급 객체 지향 프로그래밍

이터레이터 순회

three_flips = CoinFlips(3)

# 이제 이터레이터의 모든 원소를 순회해 보세요
for flip in three_flips:
    print(flip)
T
H
T
None
None
None
...
Python 중급 객체 지향 프로그래밍

StopIteration

...
    def __next__(self):
        # 동전이 "number_of_flips"번 덜 뒤집혔을 때만 실행
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])

        else:  # 아니면 StopIteration으로 중단
            raise StopIteration
  • 컬렉션/데이터 스트림의 끝을 알림
  • 무한 루프 방지
  • 처리하기 쉬움
Python 중급 객체 지향 프로그래밍

이터레이터 순회

three_flips = CoinFlips(3)

# 이제 이터레이터의 모든 원소를 순회해 보세요
for flip in three_flips:
    print(flip)
H
T
H
Python 중급 객체 지향 프로그래밍

StopIteration 예외 처리

while True:
    try:
        next(three_flips)  # three_flips의 다음 원소 꺼내기

    # StopIteration 예외 처리
    except StopIteration:
        print("모든 동전 던지기 완료!")
        break
H
H
H
모든 동전 던지기 완료!
Python 중급 객체 지향 프로그래밍

연습해 봅시다!

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...