Python 中級オブジェクト指向プログラミング
Jake Roach
Data Engineer
オブジェクト集合やデータストリームを走査し、1項目ずつ返すクラス
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)
# コインを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 中級オブジェクト指向プログラミング