Use of “global” keyword in Python

后端 未结 10 2434
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  别那么骄傲
    2020-11-21 05:33

    This is the difference between accessing the name and binding it within a scope.

    If you're just looking up a variable to read its value, you've got access to global as well as local scope.

    However if you assign to a variable who's name isn't in local scope, you are binding that name into this scope (and if that name also exists as a global, you'll hide that).

    If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.

    Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).

    >>> a = 1
    >>> def p():
        print(a) # accessing global scope, no binding going on
    >>> def q():
        a = 3 # binding a name in local scope - hiding global
        print(a)
    >>> def r():
        print(a) # fail - a is bound to local scope, but not assigned yet
        a = 4
    >>> p()
    1
    >>> q()
    3
    >>> r()
    Traceback (most recent call last):
      File "", line 1, in 
        r()
      File "", line 2, in r
        print(a) # fail - a is bound to local scope, but not assigned yet
    UnboundLocalError: local variable 'a' referenced before assignment
    >>> 
    

提交回复
热议问题