這段代碼不用在函數中聲明global x就可以打印出x的值x = 20def getx(): print xgetx()以下是一個多線程的python代碼片段,其中的x,l都是全局變量,但在threadcode()函數中只聲明了global x沒有global l。完整的代碼是可以成功運行,但是把global x注釋掉后就會報錯。請問這是為什么,Lock對象比較特殊嗎?import threading, time, sysx = 50l = 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()
...
2 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
對于Python2而言,對于一個全局變量,你的函數里如果只使用到了它的值,而沒有對其賦值(指a = XXX
這種寫法)的話,就不需要聲明global。相反,如果你對其賦了值的話,那么你就需要聲明global
。聲明global
的話,就表示你是在向一個全局變量賦值,而不是在向一個局部變量賦值。

肥皂起泡泡
TA貢獻1829條經驗 獲得超6個贊
Python的作用域解析是基于叫做LEGB(Local(本地),Enclosing(封閉),Global(全局),Built-in(內置))的規則進行操作的??聪旅娴睦?/p>
>>> x = 10>>> def foo():... x += 1... print x...>>> foo()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'x' referenced before assignment
這是因為,在一個作用域里面給一個變量賦值的時候,Python自動認為這個變量是這個作用域的本地變量,并屏蔽作用域外的同名的變量。很多時候可能在一個函數里添加一個賦值的語句會讓你從前本來工作的代碼得到一個UnboundLocalError
。
下面的是文檔中的解釋:
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
在使用列表(lists)的時候,很容易就觸發這種錯誤??聪旅孢@個例子:
>>> lst = [1, 2, 3]>>> def foo1():... lst.append(5) # 這沒有問題......>>> foo1()>>> lst[1, 2, 3, 5] >>> lst = [1, 2, 3]>>> def foo2():... lst += [5] # ... 這就有問題了!...>>> foo2()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'lst' referenced before assignment
添加回答
舉報
0/150
提交
取消