自定义迭代器

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)

# Flip the coin three times
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Python 面向对象编程进阶

遍历迭代器

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
T
H
T
None
None
None
...
Python 面向对象编程进阶

StopIteration

...
    def __next__(self):
        # Only do this if the coin hasn't been flipped "number_of_flips" times
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])

        else:  # Otherwise, stop execution with StopIteration
            raise StopIteration
  • 标记集合/数据流结束
  • 防止无限循环
  • 易于处理
Python 面向对象编程进阶

遍历迭代器

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
H
T
H
Python 面向对象编程进阶

处理 StopIteration 异常

while True:
    try:
        next(three_flips)  # Pull the next element of three_flips

    # Catch a stop iteration exception
    except StopIteration:
        print("Completed all coin flips!")
        break
H
H
H
Completed all coin flips!
Python 面向对象编程进阶

练习时间!

Python 面向对象编程进阶

Preparing Video For Download...