Python-keyword-global & nonlocal
2017-02-27 17:00
316 查看
1. global #消除python对global variable的屏蔽(shadowing)作用
1.1 如果只是 Access 变量,不必加global1.2如果在 函数中需要修改global变量,则需加global
>>> t = 5
>>> hex(id(t))
'0x64320250'
>>> def withoutGlobal():
t = 10
print("without global id of t is:",hex(id(t)))
>>> withoutGlobal()
without global id of t is: 0x643202f0
>>> def withGlobal():
global t
t = 10
print("with global id of t is:",hex(id(t)))
>>> hex(id(t))
'0x64320250'
>>> withGlobal()
with global id of t is: 0x643202f0
>>> # after call withGlobal()
>>> hex(id(t))
'0x643202f0'
>>> t
10
2.nonlocal 用在内部函数中
2.1 错误例子>>> def fun1():
x = 5 #相当于fun2()的全局变量
def fun2():
x *= x
return fun2()
>>> fun1()
UnboundLocalError: local variable 'x' referenced before assignment
2.2 正确例子
>>> def fun1():
x = 5
def fun2():
nonlocal x
x *= x
return x
return fun2()
>>> fun1()
25
相关文章推荐
- python global和nonlocal
- Python 中 global、nonlocal的使用
- [译]python中的global和nonlocal的实践
- Python3 关键字global和nonlocal
- Python的global和nonlocal关键字(学习)
- python语法32[global与nonlocal比较]
- Python中关键字global和nonlocal的区别详解
- python基础-方法嵌套、就近原则、global、nonlocal、函数即变量
- [python]global与nonlocal关键字
- python3中global 和 nonlocal 的作用域
- Python中global与nonlocal 声明
- python main函数中变量默认为global variable & SIGKILL SIGSTOP 无法捕获
- python中global 和 nonlocal 的作用域
- python中的关键字global和nonlocal
- Python nonlocal 与 global 关键字解析
- python语法[global与nonlocal比较]
- 为什么python在函数中修改"字典型全局变量"不需要global
- Python nonlocal 与 global 关键字解析
- python语法32[global与nonlocal比较]
- python global和nonlocal的使用