python中在哪些情况下必须使用global来声明全局变量?
PHPz
PHPz 2017-04-17 11:26:41
0
2
511

这段代码不用在函数中声明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()
...
PHPz
PHPz

学习是最好的投资!

reply all(2)
黄舟

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 declare global. Declaring global 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

>>> 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

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 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.

This error can easily be triggered when using lists. Look at this example:

>>> 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template