【发布时间】:2018-02-11 14:50:55
【问题描述】:
来自Google Style Guide 的词法作用域:
嵌套的 Python 函数可以引用在封闭中定义的变量 功能,但不能分配给它们。
这两个似乎一开始都检查出来了:
# Reference
def toplevel():
a = 5
def nested():
print(a + 2)
nested()
return a
toplevel()
7
Out[]: 5
# Assignment
def toplevel():
a = 5
def nested():
a = 7 # a is still 5, can't modify enclosing scope variable
nested()
return a
toplevel()
Out[]: 5
那么,为什么嵌套函数中同时引用和赋值会导致异常呢?
# Reference and assignment
def toplevel():
a = 5
def nested():
print(a + 2)
a = 7
nested()
return a
toplevel()
# UnboundLocalError: local variable 'a' referenced before assignment
【问题讨论】:
-
请注意,
print(a+2);a=7组合不起作用,但是,a=7;print(a+2)组合有效。
标签: python python-3.x