为什么这在python中不起作用?在python中,当没有对同一变量的其他引用时,我可以访问封闭作用域(这里是全局作用域),但当有引用时,我就不能访问。
解释器是否先在函数下面查找变量定义,然后假设它只是一个还没有赋值的局部变量?这里解释器的运行顺序是什么?
> a = 5
> a
Out[3]:
5
> def closure():
print(a)
> closure()
5
> def closure():
print(a)
a = "another"
return a
> closure()
UnboundLocalError: local variable 'a' referenced before assignment发布于 2017-02-06 20:27:48
将global a添加到函数的第一行。
https://stackoverflow.com/questions/42067734
复制相似问题