• Python协程


    把yield视作控制流程的方式--------------Python协程

    一个简单的协程:

    def simple_coroutine():
        print('-> coroutine started')
        x=yield
        print('-> coroutine received:',x)
    
    >>>my_coro=simple_coroutine()
    >>>next(my_coro)
    -> coroutine started
    >>>my_coro.send(42)
    -> coroutine received:42
    Traceback (most recent call last):
        ...
    StopIteration

    解释:

    1.调用simple_coroutine()函数,返回生成器对象

    2.调用next()函数,启动生成器,在yield语句出暂停

    3.传送42,yield表达式会计算出52,然后一直运行到下一个yield表达式,或者终止

    4.控制权流动到定义体末尾,生成器抛出StopIteration异常

    一个稍微复杂的案例:

    使用协程计算移动平均

    def averager():
        total=0.0
        count=0
        average=None
        while True:
            term=yield average
            total+=term
            count+=1
            average=total/count
    
    >>>coro_avg=averager()
    >>>next(coro_avg)
    >>>coro_avg.send(10)
    10.0
    >>>coro_avg.send(30)
    20.0
    >>>coro_avg.send(5)
    15.0

    装饰器------自动预激协程的好方法

    from functools import wraps
    def coroutine(func):
        @wraps(func):
        def primer(*args,**kwargs):
            gen=func(*args,**kwargs)
            next(gen)
            return gen
        return primer
  • 相关阅读:
    简单计算器--hdu1237(栈的运用)
    Bone Collector
    Red and Black---hdu1312(dfs)
    RTMP规范简单分析
    FFMPEG中最关键的结构体之间的关系
    面向对象与形而上学
    洛谷 P2913 [USACO08OCT]车轮旋转Wheel Rotation
    洛谷 P1889 士兵站队
    洛谷 P1885 Moo
    洛谷 P1683 入门
  • 原文地址:https://www.cnblogs.com/liuguangshou123/p/13582623.html
Copyright © 2020-2023  润新知