Python代码贯穿整个switcher语句

2024-09-30 05:26:14 发布

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

我正在用不和谐.pyapi,试图为bot的不同命令模拟开关/案例

我在网上看到,我可以使用switcher = { *some value* : *function* }来模拟switch/cases,但是在特定的值上,它运行每个函数,而不是相应的函数

async def command_switcher(argument, message, parameters):
    switcher= {
        ">autovc": await autovc_command_switcher(parameters[1], message, 
         parameters) if (len(parameters) > 1) else await 
         autovc_invalid(message),
        ">help": await default_help(message),
        ">vcgroup": await autovc_invalid(message)
    }
    return switcher.get(argument, "Invalid")

我调用command_switcher并传入一个参数,如果参数是">help",那么它只正确地运行default_help()函数,但是如果传入">autovc",它将运行所有3个函数

编辑:另外,如果我切换条目的顺序,它仍然有相同的结果:">help"仍然只运行自身,">autovc"仍然运行所有3个条目

编辑2解决了感谢您的评论,同时尝试按照建议创建适当的MCVE,看到dict值是函数对象的评论,我发现我错误地调用了函数,而不是引用函数对象本身。我在async/await方面也遇到了一些问题,但是将我链接到https://xinhuang.github.io/posts/2017-07-31-common-mistakes-using-python3-asyncio.html的注释也为我澄清了这个问题


Tags: 函数default编辑message参数async评论help

热门问题