我有一个字符串,其内容为函数名称,如何在Python中引用相应的函数? [英] I have a string whose content is a function name, how to refer to the corresponding function in Python?
问题描述
例如,如果我有一个名为 add
的函数,例如
For example, if I have a function called add
like
def add(x,y):
return x+y
并且我希望能够将字符串或输入转换为直接指向该函数的功能,例如
and I want the ability to convert a string or an input to direct to that function like
w=raw_input('Please input the function you want to use')
或
w='add'
是否可以使用w来引用函数 add
?
Is there any way to use w to refer to the function add
?
推荐答案
由于您正在接受用户输入,因此最安全的方法是准确定义有效输入:
Since you are taking user input, the safest way is to define exactly what is valid input:
dispatcher={'add':add}
w='add'
try:
function=dispatcher[w]
except KeyError:
raise ValueError('invalid input')
如果您要评估诸如'add(3,4)'
之类的字符串,则可以使用安全评估:
If you want to evaluate strings like 'add(3,4)'
, you could use safe eval:
eval('add(3,4)',{'__builtins__':None},dispatcher)
eval
通常在应用于用户输入时可能很危险.由于禁用 __ builtins __
且将 locals
限制为 dispatcher
,因此上述方法更为安全.比我聪明的人可能仍然会造成麻烦,但我无法告诉您该怎么做.
eval
in general could be dangerous when applied to user input. The above is safer since __builtins__
is disabled and locals
is restricted to dispatcher
. Someone cleverer than I might be able to still cause trouble, but I couldn't tell you how to do it.
警告:即使 eval(...,{'__builtins __':None},调度程序)
也是不安全,无法应用于用户输入.恶意用户可以在您的计算机上运行任意功能,如果有机会对其字符串进行评估通过 eval
.
WARNING: Even eval(..., {'__builtins__':None}, dispatcher)
is unsafe to be applied to user input. A malicious user could run arbitrary functions on your machine if given the opportunity to have his string evaluated by eval
.
这篇关于我有一个字符串,其内容为函数名称,如何在Python中引用相应的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!