根据我的理解,Python有一个单独的函数名称空间,所以如果我想在函数中使用全局变量,我可能应该使用global。

然而,我能够访问一个全局变量,即使没有全局:

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'

为什么会这样?


另请参阅第一次使用后重新分配局部变量时发生的UnboundLocalError,以了解试图分配给全局变量而不使用全局变量时发生的错误。有关如何使用全局变量的一般问题,请参阅在函数中使用全局变量。


当前回答

虽然你可以在没有global关键字的情况下访问全局变量,但如果你想修改它们,你必须使用global关键字。例如:

foo = 1
def test():
    foo = 2 # new local foo

def blub():
    global foo
    foo = 3 # changes the value of the global foo

在这里,你只是访问了list sub。

其他回答

访问名称和分配名称是不同的。在本例中,您只是访问一个名称。

如果在函数中赋值给某个变量,则假定该变量为局部变量,除非将其声明为全局变量。如果没有,就假定它是全局的。

>>> x = 1         # global 
>>> def foo():
        print x       # accessing it, it is global

>>> foo()
1
>>> def foo():   
        x = 2        # local x
        print x 

>>> x            # global x
1
>>> foo()        # prints local x
2

这就是访问名称和在作用域中绑定名称之间的区别。

如果你只是查找一个变量来读取它的值,你可以访问全局作用域和局部作用域。

但是,如果赋值给的变量的名称不在局部作用域中,则将该名称绑定到此作用域中(如果该名称也作为全局变量存在,则将隐藏它)。

如果您希望能够分配全局名称,则需要告诉解析器使用全局名称,而不是绑定新的本地名称——这就是'global'关键字所做的。

绑定块中的任何位置都会导致该块中的任何位置的名称都被绑定,这可能会导致一些看起来相当奇怪的结果(例如,UnboundLocalError突然出现在之前的工作代码中)。

>>> a = 1
>>> def p():
    print(a) # accessing global scope, no binding going on
>>> def q():
    a = 3 # binding a name in local scope - hiding global
    print(a)
>>> def r():
    print(a) # fail - a is bound to local scope, but not assigned yet
    a = 4
>>> p()
1
>>> q()
3
>>> r()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r()
  File "<pyshell#32>", line 2, in r
    print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>> 

如果没有全局关键字,可以访问全局关键字 为了能够修改它们,您需要显式地声明关键字是全局的。否则,关键字将在局部范围内声明。

例子:

words = [...] 

def contains (word): 
    global words             # <- not really needed
    return (word in words) 

def add (word): 
    global words             # must specify that we're working with a global keyword
    if word not in words: 
        words += [word]

这在Python常见问题解答中有很好的解释

What are the rules for local and global variables in Python? In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

其他答案回答了你的问题。关于Python中的名称,要知道的另一件重要的事情是,它们在每个作用域上要么是本地的,要么是全局的。

举个例子:

value = 42

def doit():
    print value
    value = 0

doit()
print value

您可能会猜测,value = 0语句将赋值给一个局部变量,而不会影响在doit()函数外部声明的同一个变量的值。您可能会更惊讶地发现上面的代码无法运行。函数内部的语句打印值产生一个UnboundLocalError。

原因是Python已经注意到,在函数的其他地方,你分配了name value,而且value也没有声明为全局的。这使它成为一个局部变量。但是当你试图打印它时,本地名称还没有定义。在这种情况下,Python不会像其他一些语言那样返回到将名称作为全局变量来查找。从本质上讲,如果在函数中任何地方定义了同名的局部变量,则无法访问全局变量。