您的位置:首页 > 编程语言 > Python开发

Python-keyword-global & nonlocal

2017-02-27 17:00 316 查看


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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: