python模擬事件觸發(fā)機(jī)制詳解
更新時(shí)間:2018年01月19日 09:17:29 作者:魂~
這篇文章主要為大家詳細(xì)介紹了python模擬事件觸發(fā)機(jī)制的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(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):
"""初始化事件管理器"""
# 事件對象列表
self.__eventQueue = Queue()
# 事件管理器開關(guān)
self.__active = False
# 事件處理線程
self.__thread = Thread(target = self.__Run)
# 這里的__handlers是一個(gè)字典,用來保存對應(yīng)的事件的響應(yīng)函數(shù)
# 其中每個(gè)鍵對應(yīng)的值是一個(gè)列表,列表中保存了對該事件監(jiān)聽的響應(yīng)函數(shù),一對多
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):
"""處理事件"""
# 檢查是否存在對該事件進(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):
"""啟動"""
# 將事件管理器設(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ù)"""
#讀者自己試著實(shí)現(xiàn)
def SendEvent(self, event):
"""發(fā)送事件,向事件隊(duì)列中存入事件"""
self.__eventQueue.put(event)
"""事件對象"""
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"
#事件源 公眾號
class PublicAccounts:
def __init__(self,eventManager):
self.__eventManager = eventManager
def WriteNewArtical(self):
#事件對象,寫了新文章
event = Event(type_=EVENT_ARTICAL)
event.dict["artical"] = u'如何寫出更優(yōu)雅的代碼\n'
#發(fā)送事件
self.__eventManager.SendEvent(event)
print(u'公眾號發(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"])
"""測試函數(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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python字典如何獲取最大和最小value對應(yīng)的key
這篇文章主要介紹了python字典如何獲取最大和最小value對應(yīng)的key問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11

