[英]`del` statement and free variables
Testing some Python code today I tried the following code: 今天测试一些Python代码我尝试了以下代码:
(The following runs on Python 3.2+, although previous versions will raise a SyntaxError
when del
is used and a variable is referenced in an enclosing scope) (以下在Python 3.2+上运行,尽管以前的版本在使用
del
时引发SyntaxError
并且在封闭范围内引用变量)
def x():
N = 200
def y():
print(N)
del N
y()
x()
NameError: free variable 'N' referenced before assignment in enclosing scope
As you can see, Python does not raises NameError: global name 'N' is not defined
, and that made me wondering about one thing which is: 正如您所看到的,Python不会引发
NameError: global name 'N' is not defined
,这使我想知道一件事:
when del
statement used withing the enclosing scope of a function to delete a free variable that's used inside a nested function like y
function here and thereafter if that free variable in our case N
was deleted through del
statement in the enclosing scope, what del
actually does is to delete the name's ( N
) value and keeps it bound to the enclosing scope ? 当
del
语句与函数的封闭范围一起使用时, del
在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
?A)这就是它引发的原因:
NameError: free variable 'N' referenced before assignment...
而不是NameError: global name 'N' is not defined
?B) How does
del
actually delete a name?B)
del
实际上如何删除名称? Does it unbind its value and keep it in a scope ?它是否解除了它的价值并将其保留在范围内?
It works like this: when you write print(N)
inside y
but do not assign to N
in y
, that means that at the time y
is defined, Python looks in its enclosing scopes to find the nearest one where the name N
is assigned. 它的工作原理是这样的:当你写
print(N)
内y
但不分配给N
在y
,这意味着,在当时y
定义,巨蟒看起来在其封闭范围就近找一个地方的名字N
分配。 It doesn't matter whether the assignment to N
happens before or after the definition of y
, or whether it's later undone with a del
; N
的赋值是否发生在y
的定义之前或之后,或者它是否随后用del
取消; it just looks for the nearest enclosing scope where an assignment to N
exists. 它只是查找最近的封闭范围,其中存在对
N
的赋值。 In this case, since N
is assigned inside x
, y
essentially makes a little note saying "when I need to get N
, I will look in the scope of x
". 在这种情况下,由于
N
是在x
内部分配的,因此y
基本上做了一个小注释,“当我需要得到N
,我将查看x
的范围”。
So when you actually call y
, it looks for N
in the scope of x
. 因此,当您实际调用
y
,它会在x
的范围内查找N
If it isn't there, you get the error. 如果它不存在,则会出现错误。 Note that you get this same error without
del
if you move the N = 100
line after the call to y
. 请注意,如果在调用
y
之后移动N = 100
行,则会在没有del
情况下得到相同的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.