可以将输入字符串转换为Python中的可调用函数对象吗? [英] Possible to turn an input string into a callable function object in Python?

查看:26
本文介绍了可以将输入字符串转换为Python中的可调用函数对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够采用一个描述Python函数的字符串并将其转换为一个函数对象,然后可以调用该对象.例如

I want to be able to take a string which describes a Python function and turn it into a function object which I can then call. For example,

myString = "def add5(x):
   return x + 5"
myFunc = myString.toFunction() <-- something like this?
print myFunc(10)     <-- should print 15

我之所以能够做到这一点,是因为我在计算机类的理论基础中提出了一个问题,该问题是在SISO(字符串输入,字符串输出)的假设下进行的.特别是,我们正在研究无法解决的问题yesOnString(P,I),如果P(I)="yes",则返回"yes",否则返回"no".因此,我希望能够以字符串形式作为参数传递函数P,然后将该函数转换为字符串,然后再调用该函数.

My desire to be able to do this arose from a problem posed in my theoretical foundations of computing class, which operates under an assumption of SISO (String in, String out). In particular, we are examining the uncomputable problem yesOnString(P,I), which returns "yes" if P(I) = "yes" and "no" otherwise. Thus I want to be able to have a function P passed in String form as a parameter, and then have the function convert the string into a function which it then calls.

推荐答案

使用内置的Python

This is possible with the Python built-in exec() function.

myString = "def myFunc(x): return x + 5"
exec( myString )  # myFunc = myString.toFunction() <-- something like this?
print( myFunc(10) )  #   <-- should print 15

如果要保持相同的命名模式

If you want to keep the same naming pattern

myString = "def add5(x): return x + 5"
exec( myString )  # myFunc = myString.toFunction() <-- something like this?
myFunc = add5
print( myFunc(10) )  #   <-- should print 15

在安全方面: exec() 执行给定的字符串,任何给定的字符串.

In terms of safety: exec() executes the given string, any given string.

import os.system
os.system("format C:")  # etc.

因此请务必小心使用它.当然不是任何形式的用户输入.

So be really careful how it's used. Certainly not on any sort of user's input.

这篇关于可以将输入字符串转换为Python中的可调用函数对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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