def generator(): print(123) yield 1 print(456) yield 2 g = generator() ret = g.__next__() print('***'ret) ret = g.send(None) #send 效果和 next一样 print('***'ret)
归纳:
1.send 获取下一个值得效果和next基本一致
2.只是在获取下一个值得时候,给上一个yield的位置传一个参数
使用send的注意事项
1.第一次使用生成器的时候,必须使用next获取一个值
2.最后一个yield不能接受外部的值
def average() sum = 0 count = 0 avg = 0 while 1: num = yield avg sum += num count += 1 avg = sum / count avg_g = average() avg_g.__next__() avg1 = avg_g.send(10) print(avg1)
def init(func): def inner(*args, **kwargs): ret = func(*args, **kwargs) g.__next__() return g return inner @init def average(): sum = 0 count = 0 avg = 0 while 1: num = yield avg sum += num count += 1 avg = sum / count g = average() avg1 = g.send(10) print(avg1)
python3.X----->yield from
def generator(): a = '123' b = 'abc' for i in a: yield i for i in b: yield i g = generator() for i in g: print(i)
def generator(): a = '123' b = 'abc' yield from a yield from b g = generator() for i in g: print(i)