问题
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.
Thank you!
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()
The outputs:
init: 5
from 2: 10
from 3: 15
from 2: 10
回答1:
As stated in the comments, global
in Python means module level.
So doing:
a = 1
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.
来源:https://stackoverflow.com/questions/20008940/python-global-keyword-behavior