Python的global 和 nonlocal

Python的global 和 nonlocal

在stackoverflow上看到一个关于Pythonglobal和nonlocal的用法,写得很易懂,这里记录下.

Compare this, without using nonlocal:

1
2
3
4
5
6
7
8
9
10
11
12
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)

inner()
print("outer:", x)

outer()
print("global:", x)

输出结果
inner: 2
outer: 1
global: 0

To this, using nonlocal, where inner()’s x is now also outer()’s x:

1
2
3
4
5
6
7
8
9
10
11
12
13
x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)

inner()
print("outer:", x)

outer()
print("global:", x)

输出结果
inner: 2
outer: 2
global: 0

使用nonlocal定义x后,内部和外部方法体内的x将指向同一内存. 全局的x变量不会改变

If we were to use global, it would bind x to the properly “global” value:

1
2
3
4
5
6
7
8
9
10
11
12
13
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)

inner()
print("outer:", x)

outer()
print("global:", x)

输出结果
inner: 2
outer: 1
global: 2

使用global定以后, 全局的x将会改变,但是方法体内没被定义的x不会变化.