在 Python 中什么是全局语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13881395/
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
In Python what is a global statement?
提问by Capurnicus
What is a global statement? And how is it used? I have read Python's official definition;
however, it doesn't make a lot of sense to me.
什么是全局语句?它是如何使用的?我已经阅读了Python 的官方定义;
然而,这对我来说没有多大意义。
采纳答案by mgilson
Every "variable" in python is limited to a certain scope. The scope of a python "file" is the module-scope. Consider the following:
python 中的每个“变量”都被限制在某个范围内。python“文件”的范围是模块范围。考虑以下:
#file test.py
myvariable = 5 # myvariable has module-level scope
def func():
x = 3 # x has "local" or function level scope.
Objects with local scope die as soon as the function exits and can never be retrieved (unless you returnthem), but within a function, you can access variables in the module level scope (or any containing scope):
具有局部作用域的对象在函数退出后立即死亡,并且永远无法检索(除非您是return它们),但是在函数中,您可以访问模块级作用域(或任何包含作用域)中的变量:
myvariable = 5
def func():
print(myvariable) # prints 5
def func2():
x = 3
def func3():
print(x) # will print 3 because it picks it up from `func2`'s scope
func3()
However, you can't use assignment on that reference and expect that it will be propagated to an outer scope:
但是,您不能在该引用上使用赋值并期望它会传播到外部作用域:
myvariable = 5
def func():
myvariable = 6 # creates a new "local" variable.
# Doesn't affect the global version
print(myvariable) # prints 6
func()
print(myvariable) # prints 5
Now, we're finally to global. The globalkeyword is the way that you tell python that a particular variable in your function is defined at the global (module-level) scope.
现在,我们终于到了global。该global关键字是你告诉蟒蛇,在你的函数特定变量是在全局(模块级)范围定义方式。
myvariable = 5
def func():
global myvariable
myvariable = 6 # changes `myvariable` at the global scope
print(myvariable) # prints 6
func()
print(myvariable) # prints 6 now because we were able
# to modify the reference in the function
In other words, you can change the value of myvariablein the module-scope from within funcif you use the globalkeyword.
换句话说,如果您使用关键字,您可以myvariable从内部更改模块范围内的值。funcglobal
As an aside, scopes can be nested arbitrarily deep:
顺便说一句,范围可以嵌套任意深度:
def func1():
x = 3
def func2():
print("x=",x,"func2")
y = 4
def func3():
nonlocal x # try it with nonlocal commented out as well. See the difference.
print("x=",x,"func3")
print("y=",y,"func3")
z = 5
print("z=",z,"func3")
x = 10
func3()
func2()
print("x=",x,"func1")
func1()
Now in this case, none of the variables are declared at the global scope, and in python2, there is no (easy/clean) way to change the value of xin the scope of func1from within func3. That's why the nonlocalkeyword was introduced in python3.x . nonlocalis an extension of globalthat allows you to modify a variable that you picked up from another scope in whatever scope it was pulled from.
现在,在这种情况下,没有一个变量都在全球范围内宣布,并在python2,不存在(易/干净)的方式来改变的值x在范围func1从内func3。这就是nonlocal在 python3.x 中引入关键字的原因。 nonlocal是它的扩展global,允许您修改从另一个作用域中提取的变量,无论它是从哪个作用域中提取出来的。
回答by Jakob Bowyer
Basically it tells the interpreter that the variable its given should be modified or assigned at the global level, rather than the default local level.
基本上它告诉解释器应该在全局级别而不是默认的本地级别修改或分配给定的变量。
回答by StoryTeller - Unslander Monica
a = 1
def f():
a = 2 # doesn't affect global a, this new definition hides it in local scope
a = 1
def f():
global a
a = 2 # affects global a
回答by vivek
You can use a global variable in other functions by declaring it as global in each function that modifies it
您可以在其他函数中使用全局变量,方法是在修改它的每个函数中将其声明为全局变量
Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.
Python 希望通过明确要求 global 关键字来确保您真正知道这就是您正在玩的东西。
See this answer
看到这个答案
回答by YOUNG
mgilson did a good job but I'd like to add some more.
mgilson 做得很好,但我想补充一些。
list1 = [1]
list2 = [1]
def main():
list1.append(3)
#list1 = [9]
list2 = [222]
print list1, list2
print "before main():", list1, list2
>>> [1] [1]
main()
>>> [1,3] [222]
print list1, list2
>>> [1, 3] [1]
Inside a function, Python assumes every variable as local variable unless you declare it as global, or you are accessing a global variable.
在函数内部,Python 假定每个变量都是局部变量,除非您将其声明为全局变量,或者您正在访问全局变量。
list1.append(2)
was possible because you are accessing the 'list1' and lists are mutable.
是可能的,因为您正在访问“list1”并且列表是可变的。
list2 = [222]
was possible because you are initializing a local variable.
是可能的,因为您正在初始化一个局部变量。
However if you uncomment #list1 = [9], you will get
但是,如果您取消注释#list1 = [9],您将得到
UnboundLocalError: local variable 'list1' referenced before assignment
It means you are trying to initialize a new local variable 'list1' but it was already referenced before, and you are out of the scope to reassign it.
这意味着您正在尝试初始化一个新的局部变量“list1”,但它之前已经被引用过,并且您超出了重新分配它的范围。
To enter the scope, declare 'list1' as global.
要进入范围,请将“list1”声明为全局。
I strongly recommend you to read thiseven though there is a typo in the end.
我强烈建议您阅读本文,即使最后有错别字。

