在Python函数中动态更改函数

2024-09-28 23:24:56 发布

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

尝试在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?你知道吗


Tags: 方法函数字符串用户test文本目标def
1条回答
网友
1楼 · 发布于 2024-09-28 23:24:56

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

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

>>> 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

这个方法在Python2中同样有效,还有一个额外的优点,即本地名称空间优化也没有被禁用。你知道吗

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

exec(initString + newTestString, globals())

但是像所有的全球人一样,这种副作用应该避免。你知道吗

相关问题 更多 >