在python中从字符串获取函数

2024-04-25 04:58:12 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以定义如下所示的函数?你知道吗

text = "def x(a):\treturn a+1"
f = ??(text)
f(1)
>> 2

Tags: 函数text定义deftreturn
3条回答

下面是另一个解决方案:

text = "def x(a):\treturn a+1"
f = {}
exec text in f
f['x'](1)
>> 2

您可以使用exec()

text = "def x(a):\treturn a+1"
exec(text)
print x(5) # gives 6
text = "lambda a: a + 1"
f = eval(text)
f(1)    # 2

相关问题 更多 >