Python-keyword-global & nonlocal

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章