实现说明
send() 向运行中的生成器注入值可以归结为函数 averager。
while True 是唯一的迭代点——其余代码顺序执行一遍。StopIteration 在其所在位置无条件抛出——前面没有任何输入检查。
使用要点
- 直接运行文件,输出会带上标签,比如
sends after close raise StopIteration——输出的每一行都能指回产生它的那次调用。 averager是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
代码会拦截坏输入吗?
这个示例不校验输入。StopIteration 在 throw 位置无条件抛出——没有任何东西守着它。
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 文件在加载时定义 averager。
主要签名是 def averager()
核心语句
except StopIteration:
print("sends after close raise StopIteration")
def averager():
total = 0.0
count = 0
average = None
while True:
# yield both pauses the generator and receives the next .send() value
value = yield average
total += value
count += 1
average = total / count
代码示例
def averager():
total = 0.0
count = 0
average = None
while True:
# yield both pauses the generator and receives the next .send() value
value = yield average
total += value
count += 1
average = total / count
avg = averager()
# the first next() "primes" the generator: it runs to the first yield and returns None
print(next(avg))
print(avg.send(10))
print(avg.send(20))
print(avg.send(30))
# close() raises GeneratorExit inside the generator and stops it for good
avg.close()
try:
avg.send(40)
except StopIteration:
print("sends after close raise StopIteration")