在Python中使用“全局”关键字

我从阅读文档的理解是,Python有一个单独的函数名称空间,如果我想在该函数中使用全局variables,我需要使用global

我正在使用Python 2.7,我试过这个小testing

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

即使没有global事情似乎也很好。 我能够访问全局variables没有任何问题。

我错过了什么? 另外,以下是Python文档:

全局语句中列出的名称不能被定义为forms参数,或者定义在for循环控制目标,类定义,函数定义或导入语句中。

虽然forms参数和类定义对我来说是有意义的,但我无法理解对循环控制目标和函数定义的限制。

global关键字只用于在本地环境中更改或创build全局variables,尽pipe创build全局variables很less被认为是一个好的解决scheme。

 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 

而如果使用global语句,则该variables将变得可用于该函数范围之外,从而有效地成为全局variables。

 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在本地上下文中声明函数,类或其他对象。 虽然我会build议反对它,因为如果出现问题或需要debugging会导致噩梦。

虽然您可以在不使用global关键字的情况下访问全局variables,但如果要修改它们,则必须使用global关键字。 例如:

 foo = 1 def test(): foo = 2 # new local foo def blub(): global foo foo = 3 # changes the value of the global foo 

在你的情况下,你只是访问列表sub

这是访问名称并在范围内绑定它的区别。

如果你只是查找一个variables来读取它的值,你可以访问全局和本地范围。

但是,如果您将名称分配给名称不在本地范围内的variables,则将该名称绑定到该范围(如果该名称也以全局方式存在,则将隐藏该名称)。

如果您希望能够分配全局名称,则需要告诉parsing器使用全局名称,而不是绑定新的本地名称,这是“全局”关键字的作用。

在块中的任何位置进行绑定都会导致该块中的任何位置的名称都被绑定,这可能会导致一些相当奇怪的后果(例如突然出现在以前工作的代码中的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 >>> 

其他答案回答你的问题。 关于Python中名称的另一个重要的事情是,它们要么是本地的,要么是全局的。

考虑这个,例如:

 value = 42 def doit(): print value value = 0 doit() print value 

你可能会猜测, value = 0语句将被赋值给一个局部variables,而不会影响在doit()函数外声明的相同variables的值。 你可能会更惊讶地发现上面的代码不会运行。 函数内的语句print value产生一个UnboundLocalError.

原因是Python已经注意到,在函数的其他地方,你赋值的名称,也没有声明global value 。 这使得它成为一个局部variables。 但是,当您尝试打印它时,本地名称尚未定义。 在这种情况下 Python 不会像其他一些语言那样回退到寻找全局variables的名字。 实质上,如果你已经在函数中的任何地方定义了一个具有相同名字的局部variables,你就不能访问一个全局variables。

这让我绊了很多次,我希望避免你跳过同样的事情。

访问名称和分配名称是不同的。 在你的情况下,你只是访问一个名字。

如果你赋值给一个函数中的一个variables,那么这个variables被认为是本地的,除非你把它声明为全局variables。 如果没有这个,它被认为是全球性的。

 >>> 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全局关键字
  • 为了能够修改它们,你需要明确指出关键字是全局的。 否则,关键字将在本地范围内声明。

例:

 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] 

任何在函数之外声明的variables都被认为是全局variables,只有在函数内部(构造函数除外)声明它们时,必须指定该variables是全局variables。

这意味着你不应该这样做:

 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" 

全球variables“全球”

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

这使得'x'在函数之外像一个正常variables一样工作。 如果你把全局取出,那么它会给出一个错误,因为它不能在函数内部打印一个variables。

 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)