這解釋了爲什麼不是工作。在這裏,a
被視爲本地,
a = 1
def fn():
print a
a = 2 # <<< We're adding this
fn()
# Throws: UnboundLocalError: local variable 'a' referenced before assignment
你可以有Python視變量作爲全球性的發言global a
。如果這樣做,那麼該變量將作爲全局對象再次被整個函數體處理。
a = 1
def fn():
global a # <<< We're adding this
print a
a = 2
fn()
print a
# Prints: 1
# Then, prints: 2 (a changed in the global scope too)
摘要
不像你所期望的是什麼,Python將不回落到全球範圍內,如果無法找到在局部範圍a
。
這意味着變量是本地或全局的對於整個函數體:它不能是全局的,然後變成本地的。
現在,關於變量是作爲本地還是全局對待,Python遵循以下規則。變量是:
- 全球如果只是引用如果
global
語句用來
- 地方如果變量被分配到至少一次(並且不使用
global
)從未分配到
- 全球
還注意到
事實上,「意蘊非常全球化「並不意味着全球化。這裏有一個更好的辦法來想一想:
- 「本地」的意思是「在函數內部某處」
- 「全球性」的真正含義「之外的功能某處」
所以,如果一個變量被「隱含全局」(==「之外的功能」),那麼它的「封閉的範圍」將被首先擡起頭來:
a = 25
def enclosing():
a = 2
def enclosed():
print a
enclosed()
enclosing()
# Prints 2, as supplied in the enclosing scope, instead of 25 (found in the global scope)
現在,像往常一樣,global
讓你引用全局SC OPE。
a = 25
def enclosing():
a = 2
def enclosed():
global a # <<< We're adding this
print a
enclosed()
enclosing()
# Prints 25, as supplied in the global scope
現在,如果你需要分配給a
在enclosed
,並希望a
適適用範圍的價值在enclosing
改變「,而不是在全球範圍內,那麼你就需要nonlocal
,這是新的在Python 3中。在Python 2中,你不能。
歸因缺失:[學習Python:強大的面向對象編程](http://goo.gl/woLW0F) –
@Aशwiniचhaudhary完成:) – ajkumar25