如何使用字符串定义函数名

ise*_*thi 2 python python-3.x

我试图创建一个更动态的程序,在其中根据变量字符串定义函数的名称。

尝试使用这样的变量定义函数:

__func_name__ = "fun"

def __func_name__():
  print('Hello from ' + __func_name__)

fun()
Run Code Online (Sandbox Code Playgroud)

想要输出:

Hello from fun
Run Code Online (Sandbox Code Playgroud)

我发现的唯一例子是: how to Define a function from a string using python

Net*_*ave 5

您可以更新globals

>>> globals()["my_function_name"] = lambda x: x + 1
>>> my_function_name(10)
11
Run Code Online (Sandbox Code Playgroud)

但通常使用具有相关功能的字典更方便:

my_func_dict = {
    "__func_name__" : __func_name__,
}

def __func_name__():
  print('Hello')
Run Code Online (Sandbox Code Playgroud)

然后使用 dict 以名称作为键来取回函数:

my_func_dict["__func_name__"]()
Run Code Online (Sandbox Code Playgroud)