我有一个字符串,其内容是一个函数名,在Python中如何引用对应的函数? [英] I have a string whose content is a function name, how to refer to the corresponding function in Python?

查看:17
本文介绍了我有一个字符串,其内容是一个函数名,在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.

这篇关于我有一个字符串,其内容是一个函数名,在Python中如何引用对应的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆