生成器函数进阶

next 与 send

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)

yield from 方法:

def generator():
    a = '123'
    b = 'abc'
    yield from a
    yield from b


g = generator()
for i in g:
    print(i)