简体   繁体   English

`del`语句和自由变量

[英]`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语句与函数的封闭范围一起使用时, dely函数这样的嵌套函数中使用的自由变量,此后如果在我们的情况下N中的自由变量是通过封闭范围中的del语句删除的,那么del实际上是什么是删除名称的( N )值并将其绑定到封闭范围?

A) Is that why it raises: NameError: free variable 'N' referenced before assignment... rather than NameError: 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 ? 它是否解除了它的价值并将其保留在范围内?

I found a similar case here 我在这里找到了类似的案例

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但不分配给Ny ,这意味着,在当时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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM