Python 物件導向程式設計進階
Jake Roach
Data Engineer
可逐一走訪物件集合或資料串流的類別,並且一次回傳一個項目。
list、tuple,但行為不同for 迴圈遍歷next() 函式$$
反覆運算器協定…
# Collection
chuck = NameIterator("Charles Carmicheal")
for letter in chuck:
print(letter)
C
h
u
...
# Data stream
fun_game = DiceGame(rolls=3)
next(fun_game) # ... and so on
4
__iter__()
... return self$$
__next__()
$$
類別必須同時定義 __iter__() 與 __next__(),才算是反覆運算器!
class CoinFlips:
def __init__(self, number_of_flips):
self.number_of_flips = number_of_flips # Store the total number of flips
self.counter = 0
def __iter__(self):
return self # Return a reference of the iterator
# Flip the next coin, return the output
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("Completed all coin flips!")
break
H
H
H
Completed all coin flips!
Python 物件導向程式設計進階