Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将字符串转换为函数名_Python_Python 3.x - Fatal编程技术网

在python中将字符串转换为函数名

在python中将字符串转换为函数名,python,python-3.x,Python,Python 3.x,我有许多相同前缀的函数。我想使用字符串的组合来调用函数 def func_plus_one(v): return v+1 def func_plus_two(v): return v+2 a='plus_one' b='plus_two' 因此,我如何使用'func_'+a和'func_'+b来使用函数?如果函数与需要引用它们的代码位于同一模块中,请使用模块的globals()。您可以使用以下方法调用a指示的函数: globals()['func_' + a](x) 如果

我有许多相同前缀的函数。我想使用字符串的组合来调用函数

def func_plus_one(v):
    return v+1

def func_plus_two(v):
    return v+2

a='plus_one'
b='plus_two'

因此,我如何使用
'func_'+a
'func_'+b
来使用函数?

如果函数与需要引用它们的代码位于同一模块中,请使用模块的
globals()
。您可以使用以下方法调用
a
指示的函数:

globals()['func_' + a](x)
如果它们在另一个模块中,请使用
getattr

getattr(some_module, func_' + a)(x)

如果函数与需要引用它们的代码位于同一模块中,请使用模块的
globals()
。您可以使用以下方法调用
a
指示的函数:

globals()['func_' + a](x)
如果它们在另一个模块中,请使用
getattr

getattr(some_module, func_' + a)(x)

您可能不应该这样做。为什么不使用
a=func\u plus\u one
并跳过字符串部分?因为“plus\u one”、“plus\u two”也用于其他字符串purposes@superb雨。。。在enumerate(['one','two','three','four']):exec(f'def func_plus{n}(v):return{v}+i')中对i,n进行动态查找是一件完全可以接受的事情。您可能不应该这样做。为什么不使用
a=func_plus_one
并跳过字符串部分呢?因为'plus_one',“plus_two”也用于其他purposes@superb雨。。。在enumerate(['one','two','three','four']):exec(f'def func_plus{n}(v):return{v}+i')