Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有动态特性的Python嵌套作用域_Python_Name Binding - Fatal编程技术网

具有动态特性的Python嵌套作用域

具有动态特性的Python嵌套作用域,python,name-binding,Python,Name Binding,需要帮助从和中理解以下句子吗 如果在封闭范围内引用了变量,则 删除该名称。编译器将引发'del'的语法错误 名字' 由于缺少示例,导致我无法在编译时再现错误,因此非常需要使用示例进行解释。以下内容提出了执行选项: def foo(): spam = 'eggs' def bar(): print spam del spam 因为spam变量正在bar的封闭范围内使用: >>> def foo(): ... spam = 'egg

需要帮助从和中理解以下句子吗

如果在封闭范围内引用了变量,则 删除该名称。编译器将引发'del'的语法错误 名字'


由于缺少示例,导致我无法在编译时再现错误,因此非常需要使用示例进行解释。

以下内容提出了执行选项:

def foo():
    spam = 'eggs'
    def bar():
        print spam
    del spam
因为
spam
变量正在
bar
的封闭范围内使用:

>>> def foo():
...     spam = 'eggs'
...     def bar():
...         print spam
...     del spam
... 
SyntaxError: can not delete variable 'spam' referenced in nested scope
Python检测到
bar
中引用了
spam
,但没有为该变量赋值,因此它会在
foo
的周围范围中查找该变量。它被分配到那里,使得
delspam
语句成为语法错误

Python 3.2中删除了此限制;您现在负责自己不删除嵌套变量;您将得到一个运行时错误(
namererror
):

>>def foo():
...     垃圾邮件=‘鸡蛋’
...     def bar():
...         打印(垃圾邮件)
...     删除垃圾邮件
...     bar()
... 
>>>foo()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第6行,在foo中
文件“”,第4行,条形图
NameError:在封闭范围中的赋值之前引用了自由变量“spam”

一个例子可以是:

>>> def outer():
...     x = 0
...     y = (x for i in range(10))
...     del x
... 
SyntaxError: can not delete variable 'x' referenced in nested scope
基本上,这意味着您不能删除内部块中使用的变量(在这种情况下是genexp)

注意,这适用于python
>>> def outer():
...     x = 0
...     y = (x for i in range(10))
...     del x
... 
SyntaxError: can not delete variable 'x' referenced in nested scope
>>> def outer():
...     x = 0
...     y = (x for i in range(10))
...     del x
... 
>>> 
#python2.7
>>> x = 0
>>> y = (x for i in range(10))
>>> del x
>>> y.next()     #this is what I'd expect: NameError at Runtime
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
NameError: global name 'x' is not defined