use*_*245 24 python string function
几天前我在网上搜索,我发现了一篇关于python词典的有趣文章.它是关于使用字典中的键来调用函数.在那篇文章中,作者定义了一些函数,然后是一个字典,其键与函数名完全相同.然后他可以从用户那里获得一个输入参数并调用相同的方法(类似于实现大小写).之后我意识到了同样的事情,但不知何故有所不同.我想知道如何实现这一点.如果我有一个功能:
def fullName( name = "noName", family = "noFamily" ):
return name += family
Run Code Online (Sandbox Code Playgroud)
现在,如果我有这样的字符串:
myString = "fullName( name = 'Joe', family = 'Brand' )"
Run Code Online (Sandbox Code Playgroud)
有没有办法执行这个查询并得到一个结果:JoeBrand
例如我记得的是我们可能会给exec()语句一个字符串,它为我们做了.但是我不确定这个特例,而且我也不知道Python的有效方法.而且我将非常感谢帮助我如何处理函数返回值,例如在我的情况下如何打印该函数返回的全名?
Fel*_*ing 43
这并不能完全回答你的问题,但也许它会有所帮助:
如上所述,eval应尽可能避免.更好的方式imo是使用字典解包.这也非常动态,不易出错.
例:
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
Run Code Online (Sandbox Code Playgroud)
Fré*_*idi 29
你可以使用eval():
myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)
Run Code Online (Sandbox Code Playgroud)
但要注意,eval()被许多人认为是邪恶的.
我知道这个问题相当陈旧,但你可以这样做:
argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)