python类中的数据封装(基于python生成器封装的协程类)
类别:脚本大全 浏览量:117
时间:2021-11-03 15:13:20 python类中的数据封装
基于python生成器封装的协程类自从python2.2提供了yield关键字之后,python的生成器的很大一部分用途就是可以用来构建协同程序,能够将函数挂起返回中间值并能从上次离开的地方继续执行。python2.5的时候,这种生成器更加接近完全的协程,因为提供了将值和异常传递回到一个继续执行的函数中,当等待生成器的时候,生成器能返回控制。
python提供的生成器设施:
- yield:能够将自己挂起,并提供一个返回值给等待方
- send:唤起一个被挂起的生成器,并能够传递一个参数,可以在生成器中抛出异常
- next:本质上相当于send(None),对每个生成器的第一次调用必须不能传递参数
- close:主动退出一个生成器
python封装
虽然python3提供了asyncio这样的异步IO库,而且也有greenlet等其他协程库,但目前的需求并不是实际的网络IO并发操作,而是需要模拟状态机的运行,因此使用协程可以很方便的模拟,并加入认为的控制,下面是封装的一个python类。
|
class Coroutine( object ): """ Base class of the general coroutine object """ STATE_RUNNING = 0 STATE_WAITING = 1 STATE_CLOSING = 2 def __init__( self ): self .state = Coroutine.STATE_WAITING self .started = False self .args = None self .routine = self ._co() def _co( self ): self .ret = None while True : self .args = yield self .ret if not self .started: self .started = True continue else : self .state = Coroutine.STATE_RUNNING self .ret = self .run( self .args) if self .state = = Coroutine.STATE_CLOSING: break self .state = Coroutine.STATE_WAITING def start( self ): """ Start the generator """ if self .routine is None : raise RuntimeError( 'NO task to start running!' ) self .started = True self .routine. next () def finish( self ): """ Finish the execution of this routine """ self .state = Coroutine.STATE_CLOSING self .routine.close() def run( self , args): """ The runing method to be executed every once time""" raise NotImplementedError def execute( self , arg_obj): """ Awake this routine to execute once time """ return self .routine.send(arg_obj) |
基于上述封装,下面实现了一个协同的生产者消费者示例:
|
class ProducerCoroutine(Coroutine): """ The Producer concrete coroutine """ def __init__( self , cnsmr): if not isinstance (cnsmr, Coroutine): raise RuntimeError( 'Consumer is not a Coroutine object' ) self .consumer = cnsmr self .consumer.start() super (ProducerCoroutine, self ).__init__() def run( self , args): print 'produce ' , args ret = self .consumer.execute(args) print 'consumer return:' , ret def __call__( self , args): """ Custom method for the specific logic """ self .start() while len (args) > 0 : p = args.pop() self .execute(p) self .finish() class ConsumerCoroutine(Coroutine): """ The Consumer concrete coroutine """ def __init__( self ): super (ConsumerCoroutine, self ).__init__() def run( self , args): print 'consumer get args: ' , args return 'hahaha' + repr (args) |
运行结果如下:
|
produce 4 consumer get args: 4 consumer return : hahaha4 produce 3 consumer get args: 3 consumer return : hahaha3 produce 2 consumer get args: 2 consumer return : hahaha2 produce 1 consumer get args: 1 consumer return : hahaha1 produce 0 consumer get args: 0 consumer return : hahaha0 |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。
原文链接:https://blog.csdn.net/u010487568/article/details/62042709
您可能感兴趣
- python使用什么函数定义匿名函数(Python匿名函数及应用示例)
- python图片aes加密(python实现AES加密和解密)
- python3和python2 兼容(Python2和Python3的共存和切换使用)
- python获取当前时间戳(Python基于datetime或time模块分别获取当前时间戳的方法实例)
- python socket 设置通信协议(详解python中TCP协议中的粘包问题)
- python 怎么解析中文(Python中一般处理中文的几种方法)
- python 元组基本操作(Python元组知识点总结)
- pythonturtle库画图代码(用Python中的turtle模块画图两只小羊方法)
- python中list用法(Python数据类型之List列表实例详解)
- markdown和python的关系(解决python Markdown模块乱码的问题)
- python包和模块管理(python的依赖管理的实现)
- python scrapy 框架原理(一步步教你用python的scrapy编写一个爬虫)
- python列表切片和分片(Python列表切片操作实例总结)
- pythonflask编写接口(Python Flask框架模板操作实例分析)
- python的mqtt循环发布(python 发送和接收ActiveMQ消息的实例)
- python抽奖转盘代码(详解python--模拟轮盘抽奖游戏)
- 杯酒人生---瓦伦丁酒杯和奥丁格啤酒(杯酒人生---瓦伦丁酒杯和奥丁格啤酒)
- 中秋节买啤酒,预算超过7元试试这8种啤酒,麦香浓郁都是真啤酒(预算超过7元试试这8种啤酒)
- CellPress旗下的6 期刊,国人友刊来了解一下吧(CellPress旗下的6期刊国人友刊来了解一下吧)
- ()
- SCI检索 SSCI检索 EI检索 ISTP检索 CSCD检索简介(SCI检索SSCI检索EI检索)
- 参考文献里期刊名称的写法,你知道吗(参考文献里期刊名称的写法)
热门推荐
- vue离线地图有哪些(vue 集成腾讯地图实现api附DEMO)
- 排序算法口诀php(PHP快速排序算法实现的原理及代码详解)
- vue 父组件向子组件传值几种方法(Vue中父组件向子组件传递数据的几种方法)
- php导出excel使用方法(PHP使用ajax的post方式下载excel文件简单示例)
- python爬虫入门代码(python爬虫基础教程:requests库二代码实例)
- mysql数据类型图解(MySQL数据库主从技术GTID大揭秘)
- vue考试链接重置(Vue实现答题功能)
- rem怎么设置适配(详解如何使用rem或viewport进行移动端适配)
- mysql自增主键创建过程(深入谈谈MySQL中的自增主键)
- mysql索引提高效率(MySql如何查看索引并实现优化)
排行榜
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9