如何在单独的文件中获取函数的函数名称?

Nee*_*imo 5 python decorator python-3.x

我正在创建一个聊天main.py机器人,commands.py它有 2 个主要文件,它运行机器人并包含机器人识别的命令。我试图从中获取函数名称commands.py,以便在main.py. 例如:

命令.py

def add():
    pass

def delete():
    pass

def change():
    pass
Run Code Online (Sandbox Code Playgroud)

基本上,我希望能够存储在变量commands = ['add', 'delete', 'change']或类似的东西中。我对装饰器没有任何经验,但这可能是使用它的好时机吗?能够使用装饰器注册命令?我愿意接受任何建议,谢谢!

Aja*_*234 1

您不必使用装饰器。相反,使用getattr

import commands #the file with bot operations
val1 = getattr(commands, 'add')()
val2 = getattr(commands, 'delete')()
val3 = getattr(commands, 'change')()
Run Code Online (Sandbox Code Playgroud)