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)是怎样的?
is correct. "an enclosing scope" refers to "within the closure", not "within the function". For functions within a closure, the reference to upvalue (the variable in the upper layer) is immutable.
Look here http://stackoverflow.com/questions/29...
local is not enclosing scope