作家
登录

Python增强的生成器:协程

作者: 来源: 2017-09-06 10:56:13 阅读 我要评论

@consumer 
  •  
  • def gen_throw(): 
  •  
  •     value = yield 
  •  
  •     try: 
  •         yield value 
  •  
  •     except Exception, e: 
  •  
  •         yield str(e) # 如不雅注释掉履┞封行,那么会抛出StopIteration      
  •  
  • if __name__ == '__main__'
  •  
  •     g = gen_throw() 
  •  
  •     assert g.send(5) == 5 
  •  
  •     assert g.throw(Exception, 'throw Exception') == 'throw Exception'  
  • 第一次调用send,代码返回value(5)之后在第5行挂起, 然后generator throw之后会被第6行catch住。如不雅第7行没有从新yield,那么会从新抛出StopIteration异常。

    留意事项

    如不雅一个生成器已经经由过程send开端履行,那么在其再次yield之前,是不克不及大年夜其他生成器再次调剂到该生成器

    1. @consumer 
    2.  
    3. def funcA(): 
    4.  
    5.     while True
    6.  
    7.         data = yield 
    8.  
    9.         print 'funcA recevie', data 
    10.  
    11.         fb.send(data * 2)      
    12.  
    13. @consumer 
    14.  
    15. def funcB(): 
    16.  
    17.     while True
    18.  
    19.         data = yield 
    20.  
    21.         print 'funcB recevie', data 
    22.  
    23.         fa.send(data * 2)      
    24.  
    25. fa = funcA() 
    26.  
    27. fb = funcB() 
    28.  
    29. if __name__ == '__main__'
    30.  
    31.     fa.send(10)  

    输出:

    1. funcA recevie 10 
    2.  
    3. funcB recevie 20 
    4.  
    5. ValueError: generator already executing  

    Generator 与 Coroutine

    Python中,generator的send和throw办法使得generator很像一个协程(coroutine), 然则generator只是一个半协程(semicoroutines),python doc是如许描述的:

    “All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than>

  • @yield_dec 
  •  
  • def do(a): 
  •  
  •     print 'do', a 
  •  

      推荐阅读

      最经典的前端面试题之一,你能答出什么幺蛾子?

    本文的目标是以“输入 URL 后产生了什么”这个经典面试题为引子,写一篇既可以或许涵盖面试中大年夜部分收集试题,又可以或许将“输入 URL 后产生什么”讲得有深度的>>>详细阅读


    本文标题:Python增强的生成器:协程

    地址:http://www.17bianji.com/lsqh/37169.html

  • 关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)