當你調用scope()
Python看到你有你的方法(從內scope
的import
),所以這掩蓋了全球os
內部使用所謂的os
的局部變量。但是,如果您說print os
您尚未到達線路並執行本地導入,那麼您在分配之前就會看到有關參考的錯誤。這裏有一對夫婦的其他例子,可以幫助:
>>> x = 3
>>> def printx():
... print x # will print the global x
...
>>> def printx2():
... print x # will try to print the local x
... x = 4
...
>>> printx()
3
>>> printx2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in printx2
UnboundLocalError: local variable 'x' referenced before assignment
而且要回你的os
例子。任何分配到os
具有相同的效果:
>>> os
<module 'os' from 'C:\CDL_INSTALL\install\Python26\lib\os.pyc'>
>>> def bad_os():
... print os
... os = "assigning a string to local os"
...
>>> bad_os()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bad_os
UnboundLocalError: local variable 'os' referenced before assignment
最後,比較這些2個例子:
>>> def example1():
... print never_used # will be interpreted as a global
...
>>> def example2():
... print used_later # will be interpreted as the local assigned later
... used_later = 42
...
>>> example1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example1
NameError: global name 'never_used' is not defined
>>> example2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example2
UnboundLocalError: local variable 'used_later' referenced before assignment
謝謝 - 但有沒有任何有關內部實施的參考?我想看看如何解析器實際工作。它是否使Python爲每個範圍創建字典/結構,並且只在內部範圍內沒有任何東西時才查找外部範圍?只是想清除我的想法。 – Almad 2010-06-28 10:02:54
這不是一個解析器問題,它是一個運行時「找到與名稱匹配x最接近的範圍」的東西。 – 2010-06-28 14:28:45