def average(): sum = 0 count = 0 avg = 0 while True: #循环 num = yield avg #遇到yield就停止,防止一开始除数为0导致崩溃 sum += num count +=1 avg = sum/count avg_g = average() #生成器获取 avg_g.__next__() #执行生成器的__next__()函数,跳到第一个yield之后 avg1 = avg_g.send(10) #执行生成器的send()函数,把10带入num,开始执行并返回avg avg2 = avg_g.send(20) print(avg1,avg2)
千万注意缩进,刚开始我while True:下面没缩进,就导致代码错误,正确输出如下:
10.0 15.0
下图是添加了装饰器,以及程序的执行步骤