如何在python中将字符串转换为函数名称? [英] How to convert a string to a function name in python?

查看:953
本文介绍了如何在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天全站免登陆