美文网首页
keyword --- global & nonloc

keyword --- global & nonloc

作者: 浪费不过白头发 | 来源:发表于2017-03-05 16:02 被阅读10次

    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


    相关文章

      网友评论

          本文标题:keyword --- global & nonloc

          本文链接:https://www.haomeiwen.com/subject/zbzawttx.html