Python:为什么我不能使用locals()修改函数中的当前作用域?
作者:互联网
为什么在函数内无法创建/修改locals()的成员?
Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Here's an example of what I expect to be possible in a function:
>>> a = 1
>>> locals()["a"] = 2
>>> print a
2
>>> # ...and here's what actually happens:
>>> def foo():
... b = 3
... locals()["b"] = 4
... print b
...
>>> foo()
3
解决方法:
为什么会这样?它旨在返回表示形式,并且从未打算用于编辑本地人. documentation警告说,它永远不能保证可以用作此类工具.
标签:python,scope,introspection 来源: https://codeday.me/bug/20191012/1899444.html