python模擬事件觸發(fā)機(jī)制詳解
本文實(shí)例為大家分享了python模擬事件觸發(fā)機(jī)制的具體代碼,供大家參考,具體內(nèi)容如下
EventManager.py
# -*- encoding: UTF-8 -*- # 系統(tǒng)模塊 from queue import Queue, Empty from threading import * class EventManager: def __init__(self): """初始化事件管理器""" # 事件對(duì)象列表 self.__eventQueue = Queue() # 事件管理器開關(guān) self.__active = False # 事件處理線程 self.__thread = Thread(target = self.__Run) # 這里的__handlers是一個(gè)字典,用來保存對(duì)應(yīng)的事件的響應(yīng)函數(shù) # 其中每個(gè)鍵對(duì)應(yīng)的值是一個(gè)列表,列表中保存了對(duì)該事件監(jiān)聽的響應(yīng)函數(shù),一對(duì)多 self.__handlers = {} # {事件類型:[處理事件的方法]} def __Run(self): """引擎運(yùn)行""" while self.__active == True: try: # 獲取事件的阻塞時(shí)間設(shè)為1秒 event = self.__eventQueue.get(block = True, timeout = 1) self.__EventProcess(event) except Empty: pass def __EventProcess(self, event): """處理事件""" # 檢查是否存在對(duì)該事件進(jìn)行監(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): """啟動(dòng)""" # 將事件管理器設(shè)為啟動(dòng) self.__active = True # 啟動(dòng)事件處理線程 self.__thread.start() def Stop(self): """停止""" # 將事件管理器設(shè)為停止 self.__active = False # 等待事件處理線程退出 self.__thread.join() def AddEventListener(self, type_, handler): """綁定事件和監(jiān)聽器處理函數(shù)""" # 嘗試獲取該事件類型對(duì)應(yīng)的處理函數(shù)列表,若無則創(chuàng)建 try: handlerList = self.__handlers[type_] except KeyError: handlerList = [] self.__handlers[type_] = handlerList # 若要注冊(cè)的處理器不在該事件的處理器列表中,則注冊(cè)該事件 if handler not in handlerList: handlerList.append(handler) def RemoveEventListener(self, type_, handler): """移除監(jiān)聽器的處理函數(shù)""" #讀者自己試著實(shí)現(xiàn) def SendEvent(self, event): """發(fā)送事件,向事件隊(duì)列中存入事件""" self.__eventQueue.put(event) """事件對(duì)象""" class Event: def __init__(self, type_=None): self.type_ = type_ # 事件類型 self.dict = {} # 字典用于保存具體的事件數(shù)據(jù)
test.py
# -*- encoding: UTF-8 -*- from threading import * from EventManager import * import time #事件名稱 新文章 EVENT_ARTICAL = "Event_Artical" #事件源 公眾號(hào) class PublicAccounts: def __init__(self,eventManager): self.__eventManager = eventManager def WriteNewArtical(self): #事件對(duì)象,寫了新文章 event = Event(type_=EVENT_ARTICAL) event.dict["artical"] = u'如何寫出更優(yōu)雅的代碼\n' #發(fā)送事件 self.__eventManager.SendEvent(event) print(u'公眾號(hào)發(fā)送新文章') #監(jiān)聽器 訂閱者 class Listener: def __init__(self,username): self.__username = username #監(jiān)聽器的處理函數(shù) 讀文章 def ReadArtical(self,event): print(u'%s 收到新文章' % self.__username) print(u'正在閱讀新文章內(nèi)容:%s' % event.dict["artical"]) """測(cè)試函數(shù)""" def test(): listner1 = Listener("thinkroom") #訂閱者1 listner2 = Listener("steve")#訂閱者2 eventManager = EventManager() #綁定事件和監(jiān)聽器響應(yīng)函數(shù)(新文章) eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical) eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical) eventManager.Start() publicAcc = PublicAccounts(eventManager) while True: publicAcc.WriteNewArtical() time.sleep(2) if __name__ == '__main__': test()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python讀取實(shí)時(shí)數(shù)據(jù)流示例
今天小編就為大家分享一篇Python讀取實(shí)時(shí)數(shù)據(jù)流示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12python實(shí)現(xiàn)給數(shù)組按片賦值的方法
這篇文章主要介紹了python實(shí)現(xiàn)給數(shù)組按片賦值的方法,實(shí)例分析了Python在指定位置進(jìn)行賦值的相關(guān)技巧,需要的朋友可以參考下2015-07-07編寫Python腳本把sqlAlchemy對(duì)象轉(zhuǎn)換成dict的教程
這篇文章主要介紹了編寫Python腳本把sqlAlchemy對(duì)象轉(zhuǎn)換成dict的教程,主要是基于Python的model類構(gòu)建一個(gè)轉(zhuǎn)換的方法,需要的朋友可以參考下2015-05-05python3 selenium自動(dòng)化測(cè)試 強(qiáng)大的CSS定位方法
今天小編就為大家分享一篇python3 selenium自動(dòng)化測(cè)試 強(qiáng)大的CSS定位方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08Python+Pyecharts實(shí)現(xiàn)散點(diǎn)圖的繪制
散點(diǎn)圖是指在回歸分析中,數(shù)據(jù)點(diǎn)在直角坐標(biāo)系平面上的分布圖,散點(diǎn)圖表示因變量隨自變量而變化的大致趨勢(shì),據(jù)此可以選擇合適的函數(shù)對(duì)數(shù)據(jù)點(diǎn)進(jìn)行擬合。本文將利用Python Pyecharts實(shí)現(xiàn)散點(diǎn)圖的繪制,需要的可以參考一下2022-06-06Python?encode()方法和decode()方法詳解
encode() 方法為字符串類型(str)提供的方法,用于將 str 類型轉(zhuǎn)換成 bytes 類型,這個(gè)過程也稱為“編碼”,這篇文章主要介紹了Python?encode()方法和decode()方法,需要的朋友可以參考下2022-12-12TensorFlow2.0使用keras訓(xùn)練模型的實(shí)現(xiàn)
這篇文章主要介紹了TensorFlow2.0使用keras訓(xùn)練模型的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02