nonlocal global

对nonlocal 关键字感到有些困惑,上手实践一下

Definition:

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function.

Use the keyword nonlocal to declare that the variable is not local.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
count = "Global"

def a():
count = 'Enclosing'#如果不事先声明,那么函数b中的nonlocal就会报错
def b():
nonlocal count
print(count)
count = 'Local'
b()
print(count)

if __name__ == '__main__':
a()
print(count)#输出Global
1
2
3
Enclosing
Local
Global

nonlocal 可以让a()中count变量变为非局部,可以让b()使用

global作为对比

1
2
3
4
5
6
if __name__ == '__main__':
a = 10
def test():
global a#没有global,则a=a+1会出错
a = a + 1
print(a)