標籤:
1、範圍介紹
python中的範圍分4種情況: L:local,局部範圍,即函數中定義的變數;
E:enclosing,嵌套的父級函數的局部範圍,即包含此函數的上級函數的局部範圍,但不是全域的;
G:globa,全域變數,就是模組層級別定義的變數; B:built-in,系統固定模組裡面的變數,比如int, bytearray等。 搜尋變數的優先順序順序依次是:範圍局部>外層範圍>當前模組中的全域>python內建範圍,也就是LEGB。
?
| 1234567 |
x = int(2.9) # int built-in g_count = 0 # globaldef outer(): o_count = 1 # enclosing def inner(): i_count = 2 # local |
當然,local和enclosing是相對的,enclosing變數相對上層來說也是local。
2、範圍產生
在Python中,只有模組(module),類(class)以及函數(def、lambda)才會引入新的範圍,其它的代碼塊(如if、try、for等)是不會引入新的範圍的,如下代碼:
?
| 1234 |
if True: x = 1;print(x)# 1 |
這個是沒有問題的,if並沒有引入一個新的範圍,x仍處在當前範圍中,後面代碼可以使用。
?
| 1234 |
def test(): x2 = 2print(x2)# NameError: name ‘x2‘ is not defined |
def、class、lambda是可以引入新範圍的。
3、變數的修改
一個不在局部範圍裡的變數預設是唯讀,如果試圖為其綁定一個新的值,python認為是在當前的局部範圍裡建立一個新的變數,也就是說在當前局部範圍中,如果直接使用外部範圍的變數,那麼這個變數是唯讀,不能修改,如:
?
| 1234567 |
count = 10def outer(): print(count) count = 100 print(count)outer()#UnboundLocalError: local variable ‘count‘ referenced before assignment |
這裡第一個print中,使用到了外部範圍的count,這樣後面count就指外部範圍中的count了,再修改就會報錯。 如果沒使用過這個變數,而直接賦值,會認為是新定義的變數,此時會覆蓋外部範圍中變數,如:
?
| 123456 |
count = 10def outer(): count = 100 print(count)outer()#100 |
內部範圍中直接聲明了count=100,後面使用count都是內部範圍的了。
4、global關鍵字
當內部範圍想修改外部範圍的變數時,就要用到global和nonlocal關鍵字了,當修改的變數是在全域範圍(global範圍)上的,就要使用global先聲明一下,代碼如下:
?
| 123456789 |
count = 10def outer(): global count print(count) count = 100 print(count)outer()#10#100 |
5、nonlocal關鍵字
global關鍵字聲明的變數必須在全域範圍上,不能嵌套範圍上,當要修改嵌套範圍(enclosing範圍,外層非全域範圍)中的變數怎麼辦呢,這時就需要nonlocal關鍵字了
?
| 1234567891011 |
def outer(): count = 10 def inner(): nonlocal count count = 20 print(count) inner() print(count)outer()#20#20 |
6、小結
(1)變數尋找順序:LEGB,範圍局部>外層範圍>當前模組中的全域>python內建範圍; (2)只有模組、類、及函數才能引入新範圍; (3)對於一個變數,內部範圍先聲明就會覆蓋外部變數,不聲明直接使用,就會使用外部範圍的變數; (4)內部範圍要修改外部範圍變數的值時,全域變數要使用global關鍵字,嵌套範圍變數要使用nonlocal關鍵字。nonlocal是python3新增的關鍵字,有了這個關鍵字,就能完美的實現閉包了。
python變數和範圍