WELCOME

不积跬步,无以至千里;不积小流,无以成江海。

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

 

posted @ 2022-03-23 20:54  Ambitious~  阅读(134)  评论(0)    收藏  举报