Python nonlocal 与 global 关键字解析
2017-03-13 10:03
597 查看
nonlocal
首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码: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
现在,在闭包里面加入nonlocal关键字进行声明:
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 时,就声明了该变量不只在嵌套函数inner()里面
才有效, 而是在整个大函数里面都有效。
global
还是一样,看一个例子: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 是对整个环境下的变量起作用,而不是对函数类的变量起作用。
相关文章推荐
- Python nonlocal 与 global 关键字解析
- Python中关键字nonlocal和global的声明与解析
- python global vs nonlocal (2)
- python nonlocal/global ---内部作用域中改变外部变量
- Python nonlocal 与 global 关键字解析
- Python nonlocal 与 global 关键字解析
- python3 nonlocal vs global
- Python nonlocal 与 global 关键字解析
- Python nonlocal 与 global 关键字解析
- 使用python解析Json字符串-获取Json字符串关键字
- 【PHP内核学习】global关键字的解析过程分析
- 【分区管理】如何确定分区索引是Global还是Local,PREFIXED 还是NON-PREFIXED
- Python3中 对local和nonlocal 关键字的改善认识(新手向)
- Python3基础 global关键字 使函数的局部变量升格为全局变量
- python global and local variable
- What is Local Index and Global Index in Partition Table? What is Prefix Index and Nonprefix Index in table?
- python 全局变量的理解(global关键字)
- Python全局变量global和局部变量 UnboundLocalError: local variable 'x' referenced before assignment
- Local, global, free variables in Python