生成器函数send方法案例:每输入一个值,求移动平均值,如下:10 20 30 40 50...10 15 20 25 30...
def avg_creater(): num = 0 count = 0 avg = 0 while True: num1 = yield avg num += num1 count += 1 avg = num/count g = avg_creater() g.__next__() avg = g.send(10) avg = g.send(20) avg = g.send(30) avg = g.send(40) avg = g.send(50) print(avg) #打印: 30.0
但是每次使用时,第一次读取数据都必须用next接收,所以可以把这一步可以用装饰器函数替代,从而不用每次调用都要先使用next预激生成器函数:
def avgcorator(f): def inner(*args,**kwargs): g = f(*args,**kwargs) g.__next__() return g return inner @avgcorator def func(): num = 0 count = 0 avg = 0 while True: num1 = yield avg num += num1 count += 1 avg = num / count g = func() avg = g.send(10) avg = g.send(20) avg = g.send(30) avg = g.send(40) avg = g.send(50) print(avg) #打印: 30.0
知识点:生成器:send装饰器