作用域介紹
python中的作用域分4種情況: L:local,局部作用域,即函數(shù)中定義的變量;
E:enclosing,嵌套的父級函數(shù)的局部作用域,即包含此函數(shù)的上級函數(shù)的局部作用域,但不是全局的;
G:globa,全局變量,就是模塊級別定義的變量; B:built-in,系統(tǒng)固定模塊里面的變量,比如int, bytearray等。 搜索變量的優(yōu)先級順序依次是:作用域局部>外層作用域>當(dāng)前模塊中的全局>python內(nèi)置作用域,也就是LEGB。
1
2
3
4
5
6
|
x = int ( 2.9 ) # int built-in g_count = 0 # global def outer(): o_count = 1 # enclosing def inner(): i_count = 2 # local |
當(dāng)然,local和enclosing是相對的,enclosing變量相對上層來說也是local。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#定義變量a >>> a = 0 >>> print a 0 #定義函數(shù)p() >>> def p(): ... print a ... >>> p() 0 #定義函數(shù)p2() >>> def p2(): ... print a ... a = 3 ... print a ... >>> p2() # 運行出錯,外部變量a先被引用,不能重新賦值 Traceback (most recent call last): File "<interactive input>" , line 1 , in <module> File "<interactive input>" , line 2 , in p2 UnboundLocalError: local variable 'a' referenced before assignment #定義函數(shù)p3() >>> def p3(): ... a = 3 # 不引用直接賦值 ... print a ... >>> p3() 3 >>> print a 0 # 外部變量a并未改變 |
以上所述是小編給大家介紹的Python中的變量和作用域詳解,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/androidshouce/archive/2016/07/13/5665629.html