1. 程式人生 > 其它 >Python的關鍵字global和nonlocal的用法說明

Python的關鍵字global和nonlocal的用法說明

關鍵字global和nonlocal的用法說明

一、global

  global關鍵字用來在函式或其他區域性作用域中使用全域性變數。

1.1 如果區域性要對全域性變數修改,而不使用global關鍵字。

1 count = 0
2 
3 def global_test():
4     count += 1
5     print(count)
6 
7 global_test()
8 
9 # >>UnboundLocalError: local variable 'count' referenced before assignment

1.2 如果區域性要對全域性變數修改,應在區域性宣告該全域性變數。 

1 count = 0
2 def global_test():
3     global count
4     count += 1
5     print(count)
6 global_test()
# >> 1

 注意:global會對原來的值(全域性變數)進行相應的修改

count = 0
def global_test():
    global count
    count += 1
    print(count)
global_test()
print(count)

# >> 1 1

 

1.3 如果區域性不宣告全域性變數,並且不修改全域性變數,則可以正常使用。

1 count = 0
2 def global_test():
3     print(count)
4 global_test()

# >> 0

 

 

二、nonlocal

  nonlocal宣告的變數不是區域性變數,也不是全域性變數,而是外部巢狀函式內的變數。

 

 1 def nonlocal_test():
 2     count = 0
 3 
 4     def test2():
 5         nonlocal count
 6         count += 1
 7         return count
 8 
 9     return test2
10 11 12 val = nonlocal_test() 13 print(val()) 14 print(val()) 15 print(val()) 16 17 # >> 1 18 # 2 19 # 3