python - Python 中函数内函数的动态变化

标签 python string exec function

尝试基于从字符串中提取函数来在 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 吗?

最佳答案

exec() 可以在函数中使用,你只需要记住新对象是在哪个命名空间中创建的。您需要从您的本地命名空间返回它:

>>> def newTest(newTestString):
...     initString = "def test(x): "
...     exec(initString + newTestString)
...     return test
... 
>>> newTest("print x + 20")
<function test at 0x10b06f848>
>>> test = newTest("print x + 20")
>>> test(10)
30

这仅适用于 Python 2,在使用 exec 时,正常的本地命名空间优化将被禁用。在 Python 3 中,给 exec() 一个命名空间来创建新对象in,然后检索新函数并返回它:

>>> def newTest(newTestString):
...     initString = "def test(x): "
...     ns = {}
...     exec(initString + newTestString, ns)
...     return ns['test']
... 
>>> newTest("print(x + 20)")
<function test at 0x110337b70>
>>> test = newTest("print(x + 20)")
>>> test(10)
30

此方法在 Python 2 中同样有效,而且还有一个额外的优点,即本地命名空间优化也不会被禁用。

原则上,您也可以指示 exec 直接在全局命名空间中工作:

exec(initString + newTestString, globals())

但像所有全局变量一样,应该避免这种副作用。

关于python - Python 中函数内函数的动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24190451/

相关文章:

python - 在 Spark 数据框中拆分列

python - 如何修复 jenkins 中的 python 模块导入错误

Swift 4 将字符串更改为 URL

c - 无法在 c 中使用 exec 和 makeargv 运行 ./program

python - 计算 CSV 中的属性值?

php - 谷歌应用引擎多语言

string - 如何在 bash 中找到两个字符串之间的公共(public)字符?

java - 如何删除那些标点符号?

php - 在同一个 VPS 上使用 php 执行 ssh 文件

php exec 如何查看进度