需要帮助理解PEP 227和Python Language Reference中的以下句子
如果在封闭的范围中引用了变量,则错误为
删除名称。编译器将为“del”引发语法错误。
姓名。
由于缺少示例,我无法在编译时重现错误,因此需要用示例进行解释。
最佳答案
以下内容提出了例外:
def foo():
spam = 'eggs'
def bar():
print spam
del spam
因为在封闭的范围内使用了
spam
变量:>>> def foo():
... spam = 'eggs'
... def bar():
... print spam
... del spam
...
SyntaxError: can not delete variable 'spam' referenced in nested scope
python检测到
bar
正在spam
中被引用,但没有为该变量分配任何内容,因此它会在周围的bar
范围中查找该变量。它被分配到那里,使foo
语句成为语法错误。这个限制在python 3.2中被删除;现在您自己不负责删除嵌套变量;您将得到一个运行时错误(
del spam
)。>>> def foo():
... spam = 'eggs'
... def bar():
... print(spam)
... del spam
... bar()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in foo
File "<stdin>", line 4, in bar
NameError: free variable 'spam' referenced before assignment in enclosing scope