Python全局关键字行为 [英] Python global keyword behavior
问题描述
我试图通过导入变量并在函数中本地修改变量来在模块之间使用全局变量.代码和输出如下.最后的输出不是我期望的,我认为应该是15,因为func3已经在全局范围内对其进行了修改.谁能解释一下为什么最后一个输出仍然是10.
I am trying to use a global variable across modules by importing the variable and modifying it locally within a function. The code and the output is below. The last output is not what I expected, I thought it should be 15 since it has been already modified in global scope by func3. Can anybody please explain why the last output is still 10.
谢谢!
test2.py
myGlobal = 5
def func3():
global myGlobal
myGlobal = 15
print "from 3: ", myGlobal
test1.py
from test2 import myGlobal, func3
def func1():
global myGlobal
myGlobal = 10
def func2():
print "from 2: ", myGlobal
print "init: ", myGlobal
func1()
func2()
func3()
func2()
输出:
init: 5
from 2: 10
from 3: 15
from 2: 10
推荐答案
如注释中所述,Python中的 global
表示模块级别.
As stated in the comments, global
in Python means module level.
这样做:
a = 1
对 a
的作用与以下完全相同:
Has the exact same effect on a
as:
def f():
global a
a = 1
f()
在这两种情况下,变量都不在模块之间共享.
And in both cases the variable is not shared across modules.
如果要在模块之间共享变量,请检查此.
If you want to share a variable across modules, check this.
这篇关于Python全局关键字行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!