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

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

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

为什么会这样?


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


当前回答

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

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

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

如果您希望能够分配全局名称,则需要告诉解析器使用全局名称,而不是绑定新的本地名称——这就是'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
>>> 

其他回答

关键字global仅用于在局部上下文中更改或创建全局变量,尽管创建全局变量很少被认为是一个好的解决方案。

def bob():
    me = "locally defined"    # Defined only in local context
    print(me)

bob()
print(me)     # Asking for a global variable

以上会给你:

locally defined
Traceback (most recent call last):
  File "file.py", line 9, in <module>
    print(me)
NameError: name 'me' is not defined

而如果使用全局语句,则变量将在函数作用域之外可用,有效地成为全局变量。

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global
    print(me)

bob()
print(me)     # Asking for a global variable

所以上面的代码会给你:

locally defined
locally defined

此外,由于python的特性,您还可以使用global在局部上下文中声明函数、类或其他对象。尽管我建议不要这样做,因为如果出现错误或需要调试,这会导致噩梦。

Global使变量为Global

def out():
    global x
    x = 1
    print(x)
    return


out()

print (x)

这使得'x'就像函数外的普通变量一样。如果你把全局变量拿出来,它就会报错,因为它不能在函数中打印变量。

def out():
     # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
    x = 1
    print(x)
    return


out()

print (x)

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

这意味着你不应该做以下事情:

x = 1

def myfunc():
  global x

  # formal parameter
  def localfunction(x):
    return x+1

  # import statement
  import os.path as x

  # for loop control target
  for x in range(10):
    print x

  # class definition
  class x(object):
    def __init__(self):
      pass

  #function definition
  def x():
    print "I'm bad"

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

例子:

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]