python中global和nonlocal用法的详细说明

时间:2023-03-08 22:17:49
python中global和nonlocal用法的详细说明

一、global

1、global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

gcount = 0

def global_test():
gcount+=1
print (gcount)
global_test()

以上代码会报错:第一行定义了全局变量,在内部函数中又对外部函数进行了引用并修改,那么python会认为它是一个局部变量,有因为内部函数没有对其gcount进行定义和赋值,所以报错。

2、如果局部要对全局变量修改,则在局部声明该全局变量

gcount = 0

def global_test():
global gcount
gcount+=1
print (gcount)
global_test()

以上输出为:1

3、如果局部不声明全局变量,并且不修改全局变量,则可以正常使用

gcount = 0

def global_test():
print (gcount)
global_test()

以上输出为:0

 二、nonlocal

1、 nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量

def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc()) make_counter_test()

  以上输出为:

1

2

3

三、混合使用

def scope_test():
def do_local():
spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
def do_nonlocal():
nonlocal spam #使用外层的spam变量
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignmane:", spam)
do_nonlocal()
print("After nonlocal assignment:",spam)
do_global()
print("After global assignment:",spam) scope_test()
print("In global scope:",spam)

以上输出为:

After local assignmane: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam