这段代码不用在函数中声明global x
就可以打印出x的值
x = 20
def getx():
print x
getx()
那请问在哪些情况下必须要使用global
声明全局变量?
以下是一个多线程的python代码片段,其中的x,l
都是全局变量,但在threadcode()
函数中只声明了global x
没有global l
。完整的代码是可以成功运行,但是把global x
注释掉后就会报错。请问这是为什么,Lock对象比较特殊吗?
import threading, time, sys
x = 50
l = threading.Lock()
def threadcode():
global x
l.acquire()
print 'Thread %s invoked.' % threading.currentThread().getName()
try:
print 'Thread %s running.' % threading.currentThread().getName()
x = x + 50
print 'Thread %s set x to %d.' % \
(threading.currentThread().getName(), x)
finally:
l.release()
...
For Python2, for a global variable, if your function only uses its value without assigning a value to it (referring to the
a = XXX
writing method), there is no need to declare global. On the contrary, if you assign a value to it, then you need to declareglobal
. Declaringglobal
means that you are assigning a value to a global variable, not a local variable.Python’s scope resolution operates based on rules called LEGB (Local, Enclosing, Global, Built-in). See the example below
This is because when assigning a value to a variable in a scope, Python automatically considers the variable to be a local variable of the scope and blocks variables with the same name outside the scope. A lot of times adding an assignment statement to a function will cause your previously working code to get a
UnboundLocalError
.The following is the explanation in the document:
This error can easily be triggered when using lists. Look at this example: