如何在python中将字符串转换为函数名称?

如何在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}, dispatcher)也是不安全,也无法应用于用户输入.恶意用户可以在您的计算机上运行任意功能,如果有机会对其字符串进行评估通过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.