9

我对 Python 开发比较陌生,在阅读语言文档时,我遇到了一行:

取消绑定被封闭范围引用的名称是非法的;编译器将报告一个 SyntaxError。

因此,在学习练习中,我试图在交互式 shell 中创建此错误,但我一直无法找到这样做的方法。我正在使用 Python v2.7.3,所以使用nonlocal关键字

def outer():
  a=5
  def inner():
     nonlocal a
     print(a)
     del a

不是一个选项,并且不使用nonlocal,当 Pythondel ainner函数中看到时,它会将其解释为尚未绑定的局部变量并引发UnboundLocalError异常。

显然,关于全局变量,这条规则有一个例外,那么我怎样才能创造一种情况,即我“非法”解除对封闭范围引用的变量名的绑定?

4

2 回答 2

10

删除必须在外部范围内进行:

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

相反,NameError当您尝试引用时会引发a a

>>> 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 中根本不再引发该错误。

于 2013-03-11T15:36:49.893 回答
5

要触发该错误,您需要在外部范围的上下文中取消绑定变量。

>>> def outer():
...  a=5
...  del a
...  def inner():  
...   print a
... 
SyntaxError: can not delete variable 'a' referenced in nested scope
于 2013-03-11T15:37:26.427 回答