Python 函數作用域 ...
1 # if True: 2 # x = 3 3 # 4 # print(x) 5 # 6 # def test(): 7 # a = 10 8 # print(a) # a未定義 9 10 ''' 11 Python中的作用域分為四種情況: 12 1.L:local,局部作用域,在函數中定義的變數 13 2.E:enclosing,嵌套的父級函數的局部作用域,包含此函數的上級函數的局部作用域,但不是全局的 14 3.G:global,全局變數,模塊級別定義的變數 15 4.B:built-in,系統固定模塊裡面的變數,如int,bytearray等。 16 17 搜尋變數優先順序:L>E>G>B 18 ''' 19 # 順序例子 20 # x = int(5.8) # built-in 21 # a = 1 # global 22 # def test1(): 23 # b = 2 # enclosing 24 # 25 # def test2(): 26 # c = 3 #local 27 # print(c) 28 # print(b) 29 # # print(c) # 未定義 30 # test2() 31 # test1() 32 33 # count = 10 34 # def outer(): 35 # print(count) 36 # # count +=1 # 不能修改全局變數,除非創建變數 37 # outer()