>>> import sys
>>> print(sys.version)
2.4.4
>>> b = 11
>>> def foo2():
... a = b
... print a, b
...
>>> foo2()
11 11
>>> def foo3():
... a = b
... b = 12
... print a, b
...
>>> foo3()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo3
UnboundLocalError: local variable 'b' referenced before assignment
>>> def foo4():
... global b
... a = b
... b = 12
... print a, b
...
>>> foo4()
11 12
問題>在foo3
,爲什麼你可以訪問全局變量未聲明的,但你仍然不能修改它。爲什麼你可以閱讀但不能修改全局值?
因爲它是有道理這樣。 – delnan 2012-02-25 19:14:45