35

全局变量在 Python 中是如何工作的?我知道全局变量是邪恶的,我只是在试验。

这在 python 中不起作用:

G = None

def foo():
    if G is None:
        G = 1

foo()

我收到一个错误:

UnboundLocalError: local variable 'G' referenced before assignment

我究竟做错了什么?

4

4 回答 4

67

您需要以下global声明:

def foo():
    global G
    if G is None:
        G = 1

在 Python 中,您分配的变量默认成为局部变量。您需要使用global将它们声明为全局变量。另一方面,您引用但未分配给的变量不会自动成为局部变量。这些变量指的是封闭范围内最接近的变量。

Python 3.x 引入了nonlocal类似于 的语句global,但将变量绑定到其最近的封闭范围。例如:

def foo():
    x = 5
    def bar():
        nonlocal x
        x = x * 2
    bar()
    return x

This function returns 10 when called.

于 2009-08-15T04:50:57.913 回答
9

You still have to declare G as global, from within that function:

G = None

def foo():
    global G
    if G is None:
        G = 1

foo()
print G

which simply outputs

1
于 2009-08-15T04:51:33.107 回答
9

You need to declare G as global, but as for why: whenever you refer to a variable inside a function, if you set the variable anywhere in that function, Python assumes that it's a local variable. So if a local variable by that name doesn't exist at that point in the code, you'll get the UnboundLocalError. If you actually meant to refer to a global variable, as in your question, you need the global keyword to tell Python that's what you meant.

If you don't assign to the variable anywhere in the function, but only access its value, Python will use the global variable by that name if one exists. So you could do:

G = None

def foo():
    if G is None:
        print G

foo()

This code prints None and does not throw the UnboundLocalError.

于 2009-08-15T05:04:52.470 回答
2

Define G as global in the function like this:

#!/usr/bin/python

G = None;
def foo():
    global G
    if G is None:
        G = 1;
    print G;

foo();

The above python prints 1.

Using global variables like this is bad practice because: http://c2.com/cgi/wiki?GlobalVariablesAreBad

于 2009-08-15T04:54:34.147 回答