python2.7 在函数中删除一个全局变量不报SyntaxError?
大家讲道理
大家讲道理 2017-04-17 11:05:10
[Python讨论组]
a = 3

def x():
  global a
  del(a)

print(a)
x()

在python2.7中执行上面这段代码并没有问题!但是在python2.7的文档中(没有锚记,大概在第10段)
有这样一句话:
It is illegal to unbind a name referenced by an enclosing scope; the compiler will report a SyntaxError.
我在SO上也看到了同样的一个提问,但是它答案给出的测试代码是这样的:

>>> def outer():
...     a=5
...     def inner():
...         nonlocal a
...         print(a)
...         del a
SyntaxError: can not delete variable 'a' referenced in nested scope

但是在python2.7中,并没有nonlocal这个关键字(事实上,我在3.2上测试上面这段代码也是没有问题的)。我想知道,如果这文档(2.7)上这句话是正确的,那么测试代码(2.7)是怎样的?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
高洛峰

是正确的。“an enclosing scope”指的是“闭包内”,不是“函数内”。对于一个闭包内的函数而言,upvalue(上一层的变量)的引用是不可变的。

伊谢尔伦

看这里 http://stackoverflow.com/questions/29...

local并非enclosing scope

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号