关键字nonlocal:是python3.X中出现的,所以在python2.x中无法直接使用.
python引用变量的顺序为: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量
python中关键字nonlocal和global区别:
一:global关键字用来在函数或其它局部作用域中使用全局变量。但是如果不使用全局变量也可以不适用global关键字声明。
In [1]: gcount = 0 In [2]: def get_global(): ...: #不修改时,不用使用global关键字 ...: return gcount ...: In [3]: def global_add(): ...: #修改时,需要使用global关键字 ...: global gcount ...: gcount += 1 ...: return gcount ...: In [4]: get_global() Out[4]: 0 In [5]: global_add() Out[5]: 1 In [6]: global_add() Out[6]: 2 In [7]: get_global() Out[7]: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
In
[
1
]
:
gcount
=
0
In
[
2
]
:
def
get_global
(
)
:
.
.
.
:
#不修改时,不用使用global关键字
.
.
.
:
return
gcount
.
.
.
:
In
[
3
]
:
def
global_add
(
)
:
.
.
.
:
#修改时,需要使用global关键字
.
.
.
:
global
gcount
.
.
.
:
gcount
+=
1
.
.
.
:
return
gcount
.
.
.
:
In
[
4
]
:
get_global
(
)
Out
[
4
]
:
0
In
[
5
]
:
global_add
(
)
Out
[
5
]
:
1
In
[
6
]
:
global_add
(
)
Out
[
6
]
:
2
In
[
7
]
:
get_global
(
)
Out
[
7
]
:
2
|
二:nonlocal关键字用来在函数或其它作用域中使用外层(非全局)变量
In [8]: def make_counter(): ...: count = 0 ...: def counter(): ...: nonlocal count ...: count += 1 ...: return count ...: return counter ...: In [9]: counter = make_counter() In [10]: counter() Out[10]: 1 In [11]: counter() Out[11]: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
In
[
8
]
:
def
make_counter
(
)
:
.
.
.
:
count
=
0
.
.
.
:
def
counter
(
)
:
.
.
.
:
nonlocal
count
.
.
.
:
count
+=
1
.
.
.
:
return
count
.
.
.
:
return
counter
.
.
.
:
In
[
9
]
:
counter
=
make_counter
(
)
In
[
10
]
:
counter
(
)
Out
[
10
]
:
1
In
[
11
]
:
counter
(
)
Out
[
11
]
:
2
|
在python2中可以设置可变变量来实现,例如列表,字典等。
链接:https://www.jianshu.com/p/ab69b83a8d8a