Python之路----生成器函数进阶

时间:2021-12-13 17:02:04
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)

next与send

归纳:

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 = ''
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 = ''
b = 'abc'
yield from a
yield from b g = generator()
for i in g:
print(i)

yield from方法: