Use of “global” keyword in Python

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

    The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis.

    Consider this, for example:

    value = 42
    
    def doit():
        print value
        value = 0
    
    doit()
    print value
    

    You can probably guess that the value = 0 statement will be assigning to a local variable and not affect the value of the same variable declared outside the doit() function. You may be more surprised to discover that the code above won't run. The statement print value inside the function produces an UnboundLocalError.

    The reason is that Python has noticed that, elsewhere in the function, you assign the name value, and also value is nowhere declared global. That makes it a local variable. But when you try to print it, the local name hasn't been defined yet. Python in this case does not fall back to looking for the name as a global variable, as some other languages do. Essentially, you cannot access a global variable if you have defined a local variable of the same name anywhere in the function.

提交回复
热议问题