在 Python 中使用“global”关键字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4693120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of "global" keyword in Python
提问by nik
What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global.
我从阅读文档中了解到,Python 有一个单独的函数命名空间,如果我想在该函数中使用全局变量,我需要使用global.
I'm using Python 2.7 and I tried this little test
我正在使用 Python 2.7,我尝试了这个小测试
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
It seems things are working fine even without global. I was able to access global variable without any problem.
即使没有global. 我能够毫无问题地访问全局变量。
Am I missing anything? Also, following is from Python documentation:
我错过了什么吗?此外,以下来自 Python 文档:
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
全局语句中列出的名称不得定义为形式参数或 for 循环控制目标、类定义、函数定义或导入语句。
While formal parameters and class definition make sense to me, I'm not able to understand the restriction on for loop control target and function definition.
虽然形式参数和类定义对我来说很有意义,但我无法理解 for 循环控制目标和函数定义的限制。
采纳答案by unode
The keyword globalis only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.
该关键字global仅用于在本地上下文中更改或创建全局变量,尽管创建全局变量很少被认为是一个好的解决方案。
def bob():
me = "locally defined" # Defined only in local context
print(me)
bob()
print(me) # Asking for a global variable
The above will give you:
以上将为您提供:
locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined
While if you use the globalstatement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.
而如果您使用该global语句,该变量将在函数作用域的“外部”可用,从而有效地成为一个全局变量。
def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)
bob()
print(me) # Asking for a global variable
So the above code will give you:
所以上面的代码会给你:
locally defined
locally defined
In addition, due to the nature of python, you could also use globalto declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.
此外,由于 Python 的特性,您还可以使用global在本地上下文中声明函数、类或其他对象。尽管我建议不要这样做,因为如果出现问题或需要调试,它会导致噩梦。
回答by user225312
Accessing a name and assigning a name are different. In your case, you are just accessing a name.
访问名称和分配名称是不同的。在您的情况下,您只是访问一个名称。
If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.
如果您在函数内分配给变量,则假定该变量是局部变量,除非您将其声明为全局变量。如果没有,则假定它是全局的。
>>> 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
回答by Ivo Wetzel
While you can access global variables without the globalkeyword, if you want to modify them you have to use the globalkeyword. For example:
虽然您可以不使用global关键字访问全局变量,但如果您想修改它们,则必须使用global关键字。例如:
foo = 1
def test():
foo = 2 # new local foo
def blub():
global foo
foo = 3 # changes the value of the global foo
In your case, you're just accessing the list sub.
在您的情况下,您只是访问 list sub。
回答by Jesus Ramos
Any variable declared outside of a function is assumed to be global, it's only when declaring them from inside of functions (except constructors) that you must specify that the variable be global.
任何在函数外部声明的变量都被假定为全局变量,只有在函数内部(构造函数除外)声明它们时,您才必须指定变量为全局变量。
回答by ikostia
It means that you should not do the following:
这意味着您不应执行以下操作:
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"
回答by pycruft
This is the difference between accessing the name and bindingit within a scope.
If you're just looking up a variable to read its value, you've got access to global as well as local scope.
如果您只是查找一个变量来读取它的值,那么您就可以访问全局和局部范围。
However if you assign to a variable who's name isn't in local scope, you are bindingthat name into this scope (and if that name also exists as a global, you'll hide that).
但是,如果您分配给名称不在本地范围内的变量,则将该名称绑定到此范围内(如果该名称也作为全局名称存在,则将隐藏该名称)。
If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.
如果您希望能够分配给全局名称,则需要告诉解析器使用全局名称而不是绑定新的本地名称 - 这就是 'global' 关键字的作用。
Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).
在块内的任何地方绑定都会导致该块中任何地方的名称都被绑定,这可能会导致一些看起来很奇怪的结果(例如 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
>>>
回答by kindall
The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis.
其他答案回答了你的问题。关于 Python 中的名称的另一件重要的事情是,它们在每个范围的基础上要么是本地的,要么是全局的。
Consider this, for example:
考虑一下,例如:
value = 42
def doit():
print value
value = 0
doit()
print value
You can probably guess that the value = 0statement will be assigning to a local variable and not affect the value of the same variable declared outside the doit()function. You may be more surprised to discover that the code above won't run.The statement print valueinside the function produces an UnboundLocalError.
您可能会猜测该value = 0语句将分配给局部变量,并且不会影响在doit()函数外部声明的同一变量的值。您可能会更惊讶地发现上面的代码不会运行。print value函数内的语句产生一个UnboundLocalError.
The reason is that Python has noticed that, elsewhere in the function, you assign the name value, and also valueis nowhere declared global. That makes it a local variable. But when you try to print it, the local name hasn't been defined yet. Python in this case does not fall backto looking for the name as a global variable, as some other languages do. Essentially, you cannot access a global variable if you have defined a local variable of the same name anywherein the function.
原因是 Python 已经注意到,在函数的其他地方,您分配了 name value,并且也value没有在任何地方声明global。这使它成为局部变量。但是当您尝试打印它时,本地名称尚未定义。在这种情况下,Python不会像其他一些语言那样退回到将名称作为全局变量查找。本质上,如果在函数的任何位置定义了同名的局部变量,则无法访问全局变量。
回答by martynas
- You can access global keywords without keyword
global - To be able to modify them you need to explicitly state that the keyword is global. Otherwise, the keyword will be declared in local scope.
- 无需关键字即可访问全局关键字
global - 为了能够修改它们,您需要明确声明关键字是全局的。否则,关键字将在本地范围内声明。
Example:
例子:
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]
回答by Michael
Global makes the variable "Global"
全局使变量“全局”
def out():
global x
x = 1
print(x)
return
out()
print (x)
This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.
这使得 '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)
回答by user7610
This is explained well in the Python FAQ
这在 Python FAQ 中有很好的解释
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
globalfor assigned variables provides a bar against unintended side-effects. On the other hand, ifglobalwas required for all global references, you'd be usingglobalall the time. You'd have to declare asglobalevery reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of theglobaldeclaration for identifying side-effects.
Python中局部变量和全局变量的规则是什么?
在 Python 中,仅在函数内部引用的变量是隐式全局变量。如果在函数体内的任何地方为变量赋值,则假定它是局部变量,除非明确声明为全局变量。
虽然起初有点令人惊讶,但仔细考虑一下就可以解释这一点。一方面,要求
global分配变量提供了防止意外副作用的障碍。另一方面,如果global所有全局引用都需要,您将一直使用global。您必须声明为global对内置函数或导入模块的组件的每个引用。这种混乱会破坏global声明识别副作用的用处。

