python 事件驱动模型_python实现事件驱动模型

#encoding: UTF-8#系统模块

from Queue importQueue, Emptyfrom threading import *

########################################################################

classEventManager:#----------------------------------------------------------------------

def __init__(self):"""初始化事件管理器"""

#事件对象列表

self.__eventQueue =Queue()#事件管理器开关

self.__active =False#事件处理线程

self.__thread = Thread(target = self.__Run)#这里的__handlers是一个字典,用来保存对应的事件的响应函数

#其中每个键对应的值是一个列表,列表中保存了对该事件监听的响应函数,一对多

self.__handlers ={}#----------------------------------------------------------------------

def __Run(self):"""引擎运行"""

while self.__active ==True:try:#获取事件的阻塞时间设为1秒

event = self.__eventQueue.get(block = True, timeout = 1)

self.__EventProcess(event)exceptEmpty:pass

#----------------------------------------------------------------------

def __EventProcess(self, event):"""处理事件"""

#检查是否存在对该事件进行监听的处理函数

if event.type_ in self.__handlers:#若存在,则按顺序将事件传递给处理函数执行

for handler in self.__handlers[event.type_]:

handler(event)#----------------------------------------------------------------------

defStart(self):"""启动"""

#将事件管理器设为启动

self.__active =True#启动事件处理线程

self.__thread.start()#----------------------------------------------------------------------

defStop(self):"""停止"""

#将事件管理器设为停止

self.__active =False#等待事件处理线程退出

self.__thread.join()#----------------------------------------------------------------------

defAddEventListener(self, type_, handler):"""绑定事件和监听器处理函数"""

#尝试获取该事件类型对应的处理函数列表,若无则创建

try:

handlerList= self.__handlers[type_]exceptKeyError:

handlerList=[]

self.__handlers[type_] =handlerList#若要注册的处理器不在该事件的处理器列表中,则注册该事件

if handler not inhandlerList:

handlerList.append(handler)#----------------------------------------------------------------------

defRemoveEventListener(self, type_, handler):"""移除监听器的处理函数"""

#读者自己试着实现

#----------------------------------------------------------------------

defSendEvent(self, event):"""发送事件,向事件队列中存入事件"""self.__eventQueue.put(event)########################################################################

"""事件对象"""

classEvent:def __init__(self, type_=None):

self.type_= type_ #事件类型

self.dict = {} #字典用于保存具体的事件数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值