python模擬事件觸發(fā)機制詳解
更新時間:2018年01月19日 09:17:29 作者:魂~
這篇文章主要為大家詳細介紹了python模擬事件觸發(fā)機制的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python模擬事件觸發(fā)機制的具體代碼,供大家參考,具體內(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()
# 事件管理器開關
self.__active = False
# 事件處理線程
self.__thread = Thread(target = self.__Run)
# 這里的__handlers是一個字典,用來保存對應的事件的響應函數(shù)
# 其中每個鍵對應的值是一個列表,列表中保存了對該事件監(jiān)聽的響應函數(shù),一對多
self.__handlers = {} # {事件類型:[處理事件的方法]}
def __Run(self):
"""引擎運行"""
while self.__active == True:
try:
# 獲取事件的阻塞時間設為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):
"""啟動"""
# 將事件管理器設為啟動
self.__active = True
# 啟動事件處理線程
self.__thread.start()
def Stop(self):
"""停止"""
# 將事件管理器設為停止
self.__active = False
# 等待事件處理線程退出
self.__thread.join()
def AddEventListener(self, type_, handler):
"""綁定事件和監(jiān)聽器處理函數(shù)"""
# 嘗試獲取該事件類型對應的處理函數(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ù)
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)聽器響應函數(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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
編寫Python腳本把sqlAlchemy對象轉(zhuǎn)換成dict的教程
這篇文章主要介紹了編寫Python腳本把sqlAlchemy對象轉(zhuǎn)換成dict的教程,主要是基于Python的model類構(gòu)建一個轉(zhuǎn)換的方法,需要的朋友可以參考下2015-05-05
python3 selenium自動化測試 強大的CSS定位方法
今天小編就為大家分享一篇python3 selenium自動化測試 強大的CSS定位方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python+Pyecharts實現(xiàn)散點圖的繪制
散點圖是指在回歸分析中,數(shù)據(jù)點在直角坐標系平面上的分布圖,散點圖表示因變量隨自變量而變化的大致趨勢,據(jù)此可以選擇合適的函數(shù)對數(shù)據(jù)點進行擬合。本文將利用Python Pyecharts實現(xiàn)散點圖的繪制,需要的可以參考一下2022-06-06
Python?encode()方法和decode()方法詳解
encode() 方法為字符串類型(str)提供的方法,用于將 str 類型轉(zhuǎn)換成 bytes 類型,這個過程也稱為“編碼”,這篇文章主要介紹了Python?encode()方法和decode()方法,需要的朋友可以參考下2022-12-12
TensorFlow2.0使用keras訓練模型的實現(xiàn)
這篇文章主要介紹了TensorFlow2.0使用keras訓練模型的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02

