[英]Storing functions in a sparse array with Python
我有一個相對較大的枚舉,其中每個成員代表一種消息類型。 客戶端將收到一條消息,其中包含與枚舉中的msg類型關聯的整數值。 對於每個msg類型,將有一個單獨的函數回調來處理msg。
我想通過使用稀疏數組(或向量)盡可能快地查找和調度回調,其中枚舉值映射到回調的索引。 這是否可能在Python中給定數組不能保存函數類型?
#pseudo code for 'enum'
class MsgType(object):
LOGIN, LOGOUT, HEARTBEAT, ... = range(n)
#handler class
class Handler(object):
def handleMsg(self, msg):
#dispatch msg to specific handler
def __onLogin(self, msg):
#handle login
def __onLogout(self, msg):
#handle logout
更新:我的術語不清楚。 我現在理解Python字典查找具有復雜性O(1),這使它們成為完美的候選者。 謝謝。
class MsgID(int):
pass
LOGIN = MsgID(0)
LOGOUT = MsgID(1)
HEARTBEAT = MsgID(2)
... # add all other message identifier numbers
class MsgType(object):
def __init__(self, id, data):
self.id = id
self.data = data
def login_handler(msg):
... # do something here
def logout_handler(msg):
... # do something here
def heartbeat_handler(msg):
... # do something here
msg_func = {
LOGIN : login_handler,
LOGOUT : logout_handler,
HEARTBEAT : heartbeat_handler,
...
}
class Handler(object):
def handleMsg(self, msg):
try:
msg_func[msg.id](msg) # lookup function reference in dict, call function
except KeyError:
log_error_mesg('message without a handler function: %d' % msg.id)
這不是嚴格需要的,但我為消息ID添加了一個int
的子類。 這樣你就可以檢查ID值是否真的是一個ID值,而不僅僅是一些隨機整數。
我假設每條消息都有一個ID值,標識它是什么類型的消息,加上一些數據。 msg_func
字典使用MsgID
值作為鍵,映射到函數引用。
你可以將所有的功能放在一個類中,但我沒有在這里做到; 它們只是功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.