Use of “global” keyword in Python

后端 未结 10 2451
既然无缘
既然无缘 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:42

    Accessing a name and assigning a name are different. In your case, you are just accessing a name.

    If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.

    >>> x = 1         # global 
    >>> def foo():
            print x       # accessing it, it is global
    
    >>> foo()
    1
    >>> def foo():   
            x = 2        # local x
            print x 
    
    >>> x            # global x
    1
    >>> foo()        # prints local x
    2
    

提交回复
热议问题