自訂反覆運算器

Python 物件導向程式設計進階

Jake Roach

Data Engineer

反覆運算器

可逐一走訪物件集合或資料串流的類別,並且一次回傳一個項目

  • 類似 listtuple,但行為不同
  • 瀏覽、轉換、產生
  • 可用 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
Python 物件導向程式設計進階

反覆運算器協定

__iter__()

  • 回傳一個反覆運算器,此處為自身參照
  • ... return self

$$

__next__()

  • 回傳集合或資料串流中的「下一個」值
  • 在此進行迭代、轉換與產生

$$

類別必須同時定義 __iter__()__next__(),才算是反覆運算器!

Python 物件導向程式設計進階

範例反覆運算器

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"])
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("Completed all coin flips!")
        break
H
H
H
Completed all coin flips!
Python 物件導向程式設計進階

一起來練習吧!

Python 物件導向程式設計進階

Preparing Video For Download...