用Python在稀疏数组中存储函数

2024-04-26 11:05:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相对较大的枚举,其中每个成员表示一个消息类型。客户端将收到一条消息,其中包含与枚举中的消息类型相关联的整数值。对于每个消息类型,都有一个单独的函数回调来处理消息。你知道吗

我希望通过使用一个稀疏数组(或向量)使回调的查找和分派尽可能快,在这个数组中枚举值映射到回调的索引。在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),这使它们成为完美的候选者。谢谢。你知道吗


Tags: 函数self消息客户端类型objectdef成员
1条回答
网友
1楼 · 发布于 2024-04-26 11:05:45
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)

它不是严格需要的,但是我为messageid添加了一个子类int,这样您就可以检查ID值是否真的是ID值,而不仅仅是某个随机整数。你知道吗

我假设每条消息中都有一个ID值,标识它是哪种消息,再加上一些数据。msg_func字典使用MsgID值作为键,映射到函数引用。你知道吗

你可以把所有的函数放在一个类中,但我这里没有这么做,它们只是函数。你知道吗

相关问题 更多 >