在Python中使用字符串调用函数

2024-04-26 01:22:50 发布

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

几天前,我在网上搜索,发现了一篇关于python字典的有趣文章。它是关于使用字典中的键来调用函数。在那篇文章中,作者定义了一些函数,然后定义了一个键与函数名完全相同的字典。然后他可以从用户那里得到一个输入参数并调用相同的方法(类似于实现case break) 在那之后,我意识到同样的事情,但不知何故不同。我想知道我怎样才能实现这一点。 如果我有一个函数:

def fullName( name = "noName", family = "noFamily" ):
    return name += family

现在如果我有一根这样的绳子:

myString = "fullName( name = 'Joe', family = 'Brand' )"

有没有办法执行这个查询并得到一个结果:JoeBrand
例如,我记得我们可能会给exec()语句一个字符串,它会帮我们完成。但我不确定这种特殊情况,也不知道Python中的有效方法。我也会非常感激帮助我如何处理函数返回值,例如在我的例子中,我如何打印该函数返回的全名?


Tags: 方法函数用户name参数字典定义文章
3条回答

您可以使用eval()

myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)

但是要小心,eval()被很多人认为是邪恶的。

我知道这个问题很老了,但你可以这样做:

argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)

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)

这并不能完全回答你的问题,但也许有助于:

如前所述,应尽可能避免eval。一个更好的方法是使用字典解包。这也是非常动态的,不易出错。

示例:

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

相关问题 更多 >