【发布时间】:2023-01-25 04:25:48
【问题描述】:
这里是发电机的新手。我的理解是,当从生成器函数 (total_average) 中断时,它将隐式触发 wrap_average 中的 StopIteration。但是 wrap_average 将 None 返回给调用者,程序不应该看到 StopIteration。
def total_average():
total = 0.0
count = 0
avg = None
print("starting average generator")
while True:
num = yield avg
if num is None:
break
total += num
count += 1
avg = total/count
def wrap_average(average_generator):
"""This is just a pipe to the generator"""
print("starting wrap_average")
avg = yield from average_generator
# Note: total_average() is the generator object. total_average is generator function
w = wrap_average(total_average())
# Execute everthing until hitting the first iterator. None being returned
print("starting the generator: ", next(w))
print(w.send(3))
print(w.send(4))
# Finish Coroutine
# ? Not sure why w.send(None) is giving me stop iteration?
w.send(None)
但是,Python 3.8 显示 StopIteration 错误。我不确定为什么?
【问题讨论】:
-
But wrap_average will return None back to the caller, and the program should not see StopIteration.wrap_average是生成器,因此抛出此异常。返回值无关紧要。 -
“但是 wrap_average 将 None 返回给调用者,”不,
wrap_average是一个生成器函数,它返回一个生成器对象.
标签: python-3.x