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
__iter__()
... return self$$
__next__()
$$
클래스가 이터레이터로 인정되려면 __iter__()와 __next__()를 모두 정의해야 합니다!
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"])
three_flips = CoinFlips(3)
# 동전을 세 번 던지기
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
three_flips = CoinFlips(3)
# 이제 이터레이터의 모든 원소를 순회해 보세요
for flip in three_flips:
print(flip)
T
H
T
None
None
None
...
...
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
three_flips = CoinFlips(3)
# 이제 이터레이터의 모든 원소를 순회해 보세요
for flip in three_flips:
print(flip)
H
T
H
while True:
try:
next(three_flips) # three_flips의 다음 원소 꺼내기
# StopIteration 예외 처리
except StopIteration:
print("모든 동전 던지기 완료!")
break
H
H
H
모든 동전 던지기 완료!
Python 중급 객체 지향 프로그래밍