1. global #消除python对global variable的屏蔽(shadowing)作用
1.1 如果只是 Access 变量,不必加global
1.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关键字的使用方法。通过具体示例对比了使用与不使用global关键字时,对全局变量操作的影响;并介绍了如何在嵌套函数中正确使用nonlocal来修改外部函数的变量。
31万+

被折叠的 条评论
为什么被折叠?



