You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化Python elif命令处理:Discord应用CLI重构方案咨询

优化Discord CLI命令处理的几种方案

方案1:用字典映射命令与处理函数

把每个命令的逻辑抽成独立函数,用字典做命令到函数的映射,直接替代冗长的elif链。字典的哈希查找是O(1)时间复杂度,不仅代码结构清晰,执行效率也比顺序判断高得多,新增命令只需要加函数和字典条目就行。

示例代码:

class DiscordApp:
    def __init__(self):
        self.last_command = None
        # 命令映射表:键是命令字符串,值是对应的处理函数
        self.command_handlers = {
            "quit": self.handle_quit,
            "prev": self.handle_prev,
            # 新增命令直接在这里添加键值对
        }

    async def handle_quit(self):
        print("| Disconnecting application.")
        await self.close()

    async def handle_prev(self):
        if not self.last_command or self.last_command == "prev":
            print("Cannot execute 'prev' command as a previous command.")
            return
        print(f"| Executing previous command '{self.last_command}'")
        await self.Handle(self.last_command)

    async def Handle(self, Cmd: str):
        if not Cmd:
            return
        self.last_command = Cmd
        # 从映射表获取处理函数,没有则走未知命令分支
        handler = self.command_handlers.get(Cmd)
        if handler:
            await handler()
        else:
            print(f"| Unknown command '{Cmd}'")

方案2:用装饰器自动注册命令

如果后续要频繁新增命令,用装饰器可以进一步简化流程——新增命令时只需要给函数加个装饰器,不用手动修改映射字典,代码扩展性更强。

示例代码:

class DiscordApp:
    def __init__(self):
        self.last_command = None
        self.command_handlers = {}

    # 定义命令注册装饰器
    def command(self, cmd_name):
        def decorator(func):
            self.command_handlers[cmd_name] = func
            return func
        return decorator

    @command("quit")
    async def handle_quit(self):
        print("| Disconnecting application.")
        await self.close()

    @command("prev")
    async def handle_prev(self):
        if not self.last_command or self.last_command == "prev":
            print("Cannot execute 'prev' command as a previous command.")
            return
        print(f"| Executing previous command '{self.last_command}'")
        await self.Handle(self.last_command)

    async def Handle(self, Cmd: str):
        if not Cmd:
            return
        self.last_command = Cmd
        handler = self.command_handlers.get(Cmd)
        if handler:
            await handler()
        else:
            print(f"| Unknown command '{Cmd}'")

补充:带参数的命令处理

如果你的命令需要接收参数(比如kick 123456),可以在处理逻辑里拆分命令字符串,适配带参数的场景:

@command("kick")
async def handle_kick(self, args):
    if not args:
        print("| Usage: kick <user_id>")
        return
    user_id = args[0]
    # 这里写踢人逻辑
    print(f"| Kicking user {user_id}")

# 修改Handle方法支持参数拆分
async def Handle(self, Cmd: str):
    if not Cmd:
        return
    parts = Cmd.strip().split(maxsplit=1)
    cmd_name = parts[0]
    args = parts[1].split() if len(parts) > 1 else []
    self.last_command = Cmd
    handler = self.command_handlers.get(cmd_name)
    if handler:
        await handler(args)
    else:
        print(f"| Unknown command '{cmd_name}'")

这两种方案都能彻底解决elif链带来的代码杂乱、可读性差的问题,而且字典查找的效率会随着命令数量增多,对比elif的优势越明显。

内容的提问来源于stack exchange,提问作者HeartOfIrons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 04:12:16