在 Python 中使用字符串调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4131864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use a string to call function in Python
提问by user435245
Some days ago I was searching on the net and I found an interesting article about python dictionaries. It was about using the keys in the dictionary to call a function. In that article the author has defined some functions, and then a dictionary with key exactly same as the function name. Then he could get an input parameter from user and call the same method (something like implementing case break) After that I realised about the same thing but somehow different. I want to know how I can implement this. If I have a function:
前几天我在网上搜索,我发现了一篇关于python词典的有趣文章。这是关于使用字典中的键来调用函数。在那篇文章中,作者定义了一些函数,然后是一个键与函数名完全相同的字典。然后他可以从用户那里获取一个输入参数并调用相同的方法(类似于实现 case break)之后我意识到相同的事情但不知何故不同。我想知道如何实现这一点。如果我有一个功能:
def fullName( name = "noName", family = "noFamily" ):
return name += family
And now if I have a string like this:
现在,如果我有这样的字符串:
myString = "fullName( name = 'Joe', family = 'Brand' )"
Is there a way to execute this query and get a result: JoeBrand
For example something I remember is that we might give a string to exec() statement and it does it for us. But I'm not sure about this special case, and also I do not know the efficient way in Python. And also I will be so grateful to help me how to handle that functions return value, for example in my case how can I print the full name returned by that function?
有没有办法执行这个查询并得到结果:JoeBrand
例如,我记得我们可能给 exec() 语句提供一个字符串,它会为我们做这件事。但是我不确定这种特殊情况,而且我也不知道 Python 中的有效方法。而且我将非常感谢帮助我如何处理该函数的返回值,例如在我的情况下,我如何打印该函数返回的全名?
采纳答案by Frédéric Hamidi
回答by Felix Kling
This does not exactly answer your question, but maybe it helps nevertheless:
这并不能完全回答你的问题,但也许它仍然有帮助:
As mentioned, evalshould be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.
如上所述,eval应尽可能避免。imo 更好的方法是使用字典解包。这也是非常动态的并且不容易出错。
Example:
例子:
def fullName(name = "noName", family = "noFamily"):
return name + family
functionList = {'fullName': fullName}
function = 'fullName'
parameters = {'name': 'Foo', 'family': 'Bar'}
print functionList[function](**parameters)
# prints FooBar
parameters = {'name': 'Foo'}
print functionList[function](**parameters)
# prints FoonoFamily
回答by kirbyfan64sos
I know this question is rather old, but you could do something like this:
我知道这个问题已经很老了,但你可以这样做:
argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)
argsdictis a dictionary of argument, globalscalls the function using a string, and **expands the dictionary to a parameter list. Much cleaner than eval. The only trouble lies in splitting up the string. A (very messy) solution:
argsdict是参数字典,globals使用字符串调用函数,并将**字典扩展为参数列表。比 干净多了eval。唯一的麻烦在于拆分字符串。一个(非常凌乱的)解决方案:
example = 'fullName(name=\'Joe\',family=\'Brand\')'
# Split at left parenthesis
funcname, argsstr = example.split('(')
# Split the parameters
argsindex = argsstr.split(',')
# Create an empty dictionary
argsdict = dict()
# Remove the closing parenthesis
# Could probably be done better with re...
argsindex[-1] = argsindex[-1].replace(')', '')
for item in argsindex:
# Separate the parameter name and value
argname, argvalue = item.split('=')
# Add it to the dictionary
argsdict.update({argname: argvalue})
# Call our function
globals()[funcname](**argsdict)

