【发布时间】:2014-06-12 17:27:38
【问题描述】:
尝试基于从字符串中提取函数在 Python 中进行一些动态函数更改:
目标是能够在运行时并根据用户输入,用从字符串解释的新函数替换函数。
我一直在尝试使用 exec 函数将文本解释为函数,但在更新其他函数中的函数时它似乎不起作用。
到目前为止我所拥有的是
>>> exec( "def test(x): print( x + 8 )" )
>>> test(8)
16
不过,这很好用-
>>> def newTest( newTestString ):
initString = "def test(x): "
exec( initString + newTestString )
>>> newTest( "print( x + 20 )" )
>>> test(10)
18
失败了,可以在函数中使用 exec 吗?
【问题讨论】:
-
这是 Python 2 还是 3?
标签: python string exec function