python函数作用域和global nonlocal关键字
一、作用域
简单来说,一个函数只能调用内置作用域(builtin)全局作用域(global)或者是这个函数自己的局部作用域(local),查找的顺序是从内向外的,首先查找局部作用域,然后是外层嵌套函数的作用域,再是全局作用域,最后是内置作用域。
二、global关键字
global关键字可以将函数内定义的变量声明为全局变量,而不是默认的局部变量、
X = 99
def setX(new):
global X
X = new
setX(10)
print(X)
10
三、nonlocal关键字
nonlocal声明的变量必须再一个外层的def中进行过定义,否则会引发一个错误,nonlocal的作用是将被查找的范围限定在外层def中,nonlocal语句的主要作用是让外层def作用域中的名称可以被修改,而不是只能被引用。
def tester(start):
state = start
def nested(label):
print(label, state)
return nested
F = tester(0)
F('spam')
F('ham')
spam 0
ham 0
针对上面的嵌套函数,如果我们再内层函数中修改state的值,再默认情况下这是不被允许的。
def tester(start):
state = start
def nested(label):
print(label, state)
state += 1
return nested
F = tester(0)
F('spam')
F('ham')
会报错,这个state满足nonlocal的声明条件,首先它已经在外层def中被创建了,我们可以在内层def中使用nonlocal对其进行声明,使其可以被修改。
def tester(start):
state = start
def nested(label):
nonlocal state
print(label, state)
state += 1
return nested
F = tester(0)
F('spam')
F('ham')
spam 0
ham 1