Python global keyword behavior

情到浓时终转凉″ 提交于 2021-02-11 08:26:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!