在Python中使用“global”关键字
我从阅读文档中了解到,Python有一个单独的函数命名空间,如果我想在该函数中使用全局变量,我需要使用global。
我正在使用Python 2.7,我尝试了这个小测试
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
即使没有global,似乎事情仍然正常。我能够毫无问题地访问全局变量。
我错过了什么吗? 另外,以下是来自Python文档:
全局声明中列出的名称 不得被定义为正式的 参数或for循环控制 目标,类定义,功能 定义或导入语句。
虽然形式参数和类定义对我有意义,但我无法理解for循环控制目标和函数定义的限制。
10个解决方案
328 votes
关键字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
print me
NameError: name 'me' is not defined
如果使用global语句,则变量将在函数范围“可用”之外,有效地成为全局变量。
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在本地上下文中声明函数,类或其他对象。 虽然我会反对它,因为如果出现问题或需要调试它会导致噩梦。
unode answered 2019-02-17T23:11:32Z
192 votes
虽然您可以在不使用sub关键字的情况下访问全局变量,但如果要修改它们,则必须使用global关键字。 例如:
foo = 1
def test():
foo = 2 # new local foo
def blub():
global foo
foo = 3 # changes the value of the global foo
在您的情况下,您只需访问列表sub。
Ivo Wetzel answered 2019-02-17T23:12:03Z
66 votes
这是访问名称和在范围内绑定它之间的区别。
如果您只是查找变量来读取其值,则可以访问全局和本地范围。
但是,如果您为名称不在本地范围内的变量分配,则将该名称绑定到此范围(如果该名称也作为全局存在,则会隐藏该名称)。
如果您希望能够分配全局名称,则需要告诉解析器使用全局名称而不是绑定新的本地名称 - 这就是'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 "", line 1, in
r()
File "", line 2, in r
print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>>
pycruft answered 2019-02-17T23:12:54Z
47 votes
其他答案回答了你的问题。 关于Python中名称的另一个重要事项是,它们在每个范围的基础上是本地的或全局的。
考虑一下,例如:
value = 42
def doit():
print value
value = 0
doit()
print value
您可能猜测value语句将分配给局部变量,而不会影响在value函数外声明的同一变量的值。 您可能会更惊讶地发现上面的代码无法运行。 函数内部的语句print value生成UnboundLocalError.
原因是Python注意到,在函数的其他地方,您指定了名称value,并且value也没有声明为global。这使它成为局部变量。 但是当您尝试打印它时,尚未定义本地名称。 在这种情况下,Python不会像其他语言那样回归到将名称作为全局变量查找。 实际上,如果在函数中的任何位置定义了同名的局部变量,则无法访问全局变量。
kindall answered 2019-02-17T23:13:40Z
12 votes
访问名称和分配名称是不同的。 在您的情况下,您只是访问一个名称。
如果分配给函数中的变量,则假定该变量是本地变量,除非您将其声明为全局变量。 如果没有,则假定它是全球性的。
>>> 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
user225312 answered 2019-02-17T23:14:12Z
6 votes
您可以访问不含关键字global的全局关键字
为了能够修改它们,您需要明确声明关键字是全局的。 否则,关键字将在本地范围内声明。
例:
words = [...]
def contains (word):
global words #
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]
martynas answered 2019-02-17T23:14:46Z
2 votes
在函数外部声明的任何变量都假定为全局变量,只有在从函数内部(构造函数除外)声明它们时才必须指定该变量是全局变量。
Jesus Ramos answered 2019-02-17T23:15:11Z
0 votes
这意味着您不应该执行以下操作:
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"
ikostia answered 2019-02-17T23:15:37Z
0 votes
全球使变量“全球”
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)
Michael answered 2019-02-17T23:16:09Z
0 votes
我会举个简单的例子:想想这段代码:
myVar = 0
print (myVar ) # 01 line: returns 0
def func():
myVar = "def"
print (myVar )
func() # 02 line: returns def
print (myVar ) # 03 line: returns 0
正如你所看到的最后一行代码将返回0,因为在函数内部myVar变量没有被重新分配,它只是被修改了它只会在调用函数时改变而不影响主myVar变量,因为它在里面定义了 我们的函数(意思是它是局部变量),但是使用全局关键字:
myVar = 0
print (myVar ) # 01 Line : returns 0
def func():
global myVar
myVar = "def"
print (myVar )
func() # 02 Line : returns def
print (myVar ) # 03 Line : returns def
我们实际上命令python,def中的这个变量不是本地的,使用名为myVar的全局变量来改变它。
a_m_dev answered 2019-02-17T23:16:48Z