这是个计算斐波那切数列的代码, 为了说明 async/await 的使用, 但不明白为什么 StopIteration 会获得最终结果
class Thing: def __init__(self, n): self._n = n def __await__(self): # Thing 是 iterator return (yield self) # 这里每次迭代返回 Thing 对象实例自身? def thing_interceptor(coro): value_to_send = None while True: try: thing = coro.send(value_to_send) # 把 value_to_send send 进去干嘛? 可不可以理解为没什么用, 等同于一次 next? value_to_send = thing._n # value_to_send 的值是 1 或 0 except StopIteration as exc: return exc.value async def f(n): if n <= 1: value = await Thing(n) else: value = await f(n-2) + await f(n-1) # 为什么两个 Thing 能相加, 也没实现 add 啊? return value # 最终返回 Thing 对象 coro = f(3) print(thing_interceptor(coro)) 这里我把原文的一些注释去掉了, 原文链接: https://gist.github.com/erikbern/ad7615d22b700e8dbbafd8e4d2f335e1
