yield from 语句说明
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def accumulate():
tally = 0
while 1:
next = yield
if next is None:
return tally
tally += next
def gather_tallies(tallies):
"""
这里的 gather_tallies 返回 g 的也是一个生成器,当对 g 执行next的时候,它将会执行到yield from这里。
在yield from 语句中,将创建一个子例程,同时对这个子例程自动调用一次 next() 函数。
"""
while 1:
# yield from 指的是返回一个子协程,供上层函数调用
tally = yield from accumulate()
tallies.append(tally)
print('finish')
tallies = []
acc = gather_tallies(tallies)
# 这里用来保证执行到了 yield from处,已经产生了第一个子协程
next(acc)
for i in range(4):
acc.send(i)
# 结束了第一个子协程,同时产生了第二个子协程以供调用
acc.send(None)
for i in range(5):
acc.send(i)
acc.send(None)
print(tallies)