1
也許我的咖啡是不是今天早上足夠強大,但是這種行爲是困惑我現在:(請注意,它是print a
聲明,一個人要養的錯誤func2()
,不a = 'bar'
)在函數的上下文中設置全局變量的值會引發UnboundLocalError?
>>> a = 'foo'
>>> def func1():
... print a
...
>>> def func2():
... print a
... a = 'bar'
...
>>> func1()
foo
>>> func2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func2
UnboundLocalError: local variable 'a' referenced before assignment
有人可以向我解釋發生了什麼事嗎?
可能重複的[Python作用域](http://stackoverflow.com/questions/146359/python-scope) – 2011-03-18 16:34:49