测试一些Python代码我尝试下面的代码:`del`陈述和自由变量
(关于Python 3.2+下运行,虽然以前的版本将引发SyntaxError
时del
使用和变量被引用在一个封闭的范围)
def x():
N = 200
def y():
print(N)
del N
y()
x()
NameError: free variable 'N' referenced before assignment in enclosing scope
正如你所看到的,Python不提高NameError: global name 'N' is not defined
,这让我想知道的一件事是:
时del
声明我们ED withing函数的封闭范围内删除的喜欢这里,然后y
函数嵌套函数内使用,如果在我们的例子N
自由变量是通过del
声明封闭范围中删除一个自由变量,实际上,它只是删除的内容del
该名称的(N
)值并将其保持在封闭范围内?
A) Is that why it raises:
NameError: free variable 'N' referenced before assignment...
rather thanNameError: global name 'N' is not defined
?B) How does
del
actually delete a name? Does it unbind its value and keep it in a scope ?
我发现了一个类似的案件here
的Python 2.7.3引发'语法错误:无法删除变量“N”嵌套scope'这实际上更有意义比3.2做参照。 –
对不起,你的第一个问题是什么? –
@DanD。 Python 2.7在定义'x'时也会捕获错误,而不是在调用'x'时。我认为它与Python 3中添加的'nonlocal'语句有关,但我不确定这是如何应用的(因为不使用'nonlocal')。 – chepner