本文實例為大家分享了python實現(xiàn)事件驅(qū)動的具體代碼,供大家參考,具體內(nèi)容如下
EventManager事件管理類實現(xiàn),大概就百來行代碼左右。
# encoding: UTF-8# 系統(tǒng)模塊from Queue import Queue, Emptyfrom threading import *#################################################class EventManager: #---------------------------------------------------------------------- def __init__(self): """初始化事件管理器""" # 事件對象列表 self.__eventQueue = Queue() # 事件管理器開關(guān) self.__active = False # 事件處理線程 self.__thread = Thread(target = self.__Run) # 這里的__handlers是一個字典,用來保存對應(yīng)的事件的響應(yīng)函數(shù) # 其中每個鍵對應(yīng)的值是一個列表,列表中保存了對該事件監(jiān)聽的響應(yīng)函數(shù),一對多 self.__handlers = {} #---------------------------------------------------------------------- def __Run(self): """引擎運行""" while self.__active == True: try: # 獲取事件的阻塞時間設(shè)為1秒 event = self.__eventQueue.get(block = True, timeout = 1) self.__EventProcess(event) except Empty: pass #---------------------------------------------------------------------- def __EventProcess(self, event): """處理事件""" # 檢查是否存在對該事件進行監(jiān)聽的處理函數(shù) if event.type_ in self.__handlers: # 若存在,則按順序?qū)⑹录鬟f給處理函數(shù)執(zhí)行 for handler in self.__handlers[event.type_]: handler(event) #---------------------------------------------------------------------- def Start(self): """啟動""" # 將事件管理器設(shè)為啟動 self.__active = True # 啟動事件處理線程 self.__thread.start() #---------------------------------------------------------------------- def Stop(self): """停止""" # 將事件管理器設(shè)為停止 self.__active = False # 等待事件處理線程退出 self.__thread.join() #---------------------------------------------------------------------- def AddEventListener(self, type_, handler): """綁定事件和監(jiān)聽器處理函數(shù)""" # 嘗試獲取該事件類型對應(yīng)的處理函數(shù)列表,若無則創(chuàng)建 try: handlerList = self.__handlers[type_] except KeyError: handlerList = [] self.__handlers[type_] = handlerList # 若要注冊的處理器不在該事件的處理器列表中,則注冊該事件 if handler not in handlerList: handlerList.append(handler) #---------------------------------------------------------------------- def RemoveEventListener(self, type_, handler): """移除監(jiān)聽器的處理函數(shù)""" #讀者自己試著實現(xiàn) #---------------------------------------------------------------------- def SendEvent(self, event): """發(fā)送事件,向事件隊列中存入事件""" self.__eventQueue.put(event) ########################################################################"""事件對象"""class Event: def __init__(self, type_=None): self.type_ = type_ # 事件類型 self.dict = {} # 字典用于保存具體的事件數(shù)據(jù)
新聞熱點
疑難解答