尝试在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()
可以很好地用在函数中,您只需要记住新对象是在哪个名称空间中创建的。您需要从本地命名空间返回它:这只适用于python2,在python2中,当使用
exec
时,将禁用正常的本地命名空间优化。在Python3中,给exec()
一个名称空间来创建中的新对象,然后检索新函数并返回它:这个方法在Python2中同样有效,还有一个额外的优点,即本地名称空间优化也没有被禁用。你知道吗
原则上,您也可以指示
exec
直接在全局命名空间中工作:但是像所有的全球人一样,这种副作用应该避免。你知道吗
相关问题 更多 >
编程相关推荐