我是 Python 开发的新手,在阅读语言文档时,我遇到了这样一行:
It is illegal to unbind a name that is referenced by an enclosing scope; the compiler will report a SyntaxError.
所以在学习练习中,我试图在交互式 shell 中创建此错误,但我一直无法找到这样做的方法。我使用的是 Python v2.7.3,所以使用 nonlocal 关键字
def outer():
a=5
def inner():
nonlocal a
print(a)
del a
不是一个选项,并且在不使用 nonlocal 的情况下,当 Python 在 inner
函数中看到 del a
时,它会将其解释为本地未绑定(bind)的变量并抛出 UnboundLocalError
异常。
显然,对于全局变量,此规则有一个异常(exception),那么我如何创建一种情况,让我“非法”解除绑定(bind)一个被封闭范围引用的变量名?
最佳答案
删除必须发生在外部范围内:
>>> def foo():
... a = 5
... def bar():
... return a
... del a
...
SyntaxError: can not delete variable 'a' referenced in nested scope
Python 3 中删除了编译时限制:
$ python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:08)
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
... a = 5
... def bar():
... return a
... del a
... return bar
...
>>>
相反,当您尝试引用 a
时会引发 NameError
:
>>> foo()()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in bar
NameError: free variable 'a' referenced before assignment in enclosing scope
我很想在这里提交文档错误。对于 Python 2,文档具有误导性;它正在删除在触发编译时错误的嵌套范围内使用的变量,并且在 Python 3 中根本不再引发错误。
关于Python变量命名/绑定(bind)混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342545/