def generator():
print(12)
num=yield 12
print("**",num)
print(52)
yield 445
g=generator()#把这个函数传给g,变成一个生成器
ret=g.__next__()
print(ret)
ret=g.send("hello")#它的效果和__next__相同,在读取下一步内容的同时,给上个yield传个值
print(ret)
#send()使用的注意事项
1.第一次使用生成器的时候,必须要用__next__传值
2.最后一个yield不能获取外部的值
#获取移动平均值
def average():
sum=0
count=0
avg=0
while 1:
num=yield avg
num=yield
sum+=num
count+=1
avg=sum/count
g=average()
g.__next__()
ret=g.send(10)
ret=g.send(20)
print(ret)
def init(f):
def inner(*avgs,**kavgs):
g=f(*avgs,**kavgs)
g.__next__()
return inner
@init
def generator():
avg=0
sum=0
count=0
while 1:
num=yield avg
sum+=num
count+=1
avg=sum/count
avg_g=generator()
avg_g.__next__()
ret=avg_g.send(10)
ret=avg_g.send(30)
ret=avg_g.send(20)
print(ret)
原文地址:https://www.cnblogs.com/648071634com/p/11663110.html