[英]Understanding global variable in Python
I came across a strange issue in Python when using global variables. 在使用全局变量时,我在Python中遇到了一个奇怪的问题。
I have two modules(files): mod1.py
and mod2.py
我有两个模块(文件): mod1.py
和mod2.py
mod1
tries to modify the global variable var
defined in mod2
. mod1
尝试修改mod2
定义的全局变量var
。 But the var
in mod2 and var
in mod
seems to be two different things. 但var
在mod2和var
在mod
似乎是两个不同的东西。 Thus, the result shows that such modification does not work. 因此,结果表明这种修改不起作用。
Here is the code: 这是代码:
#code for mod2.py
global var
var = 1
def fun_of_mod2():
print var
#code for mod1.py
from mod2 import var,fun_of_mod2
global var #commenting out this line yields the same result
var = 2 #I want to modify the value of var defined in mod2
fun_of_mod2() #but it prints: 1 instead of 2. Modification failed :-(
Any hint on why this happens? 有关为何会发生这种情况的任何提示 And how can I modify the value of val
defined in mod2
in mod1
? 如何修改mod1
中mod2
中定义的val
的值?
Thanks 谢谢
When you import var
into mod1
: 将var
导入mod1
:
from mod2 import var,fun_of_mod2
You are giving it the name var
in mod1's namespace. 你在mod1的命名空间中给它命名var
。 It is as if you did this: 好像你这样做了:
import mod2
var = mod2.var
fun_of_mod2 = mod2.fun_of_mod2
del mod2
In other words, there are now two names for the value, mod1.var
and mod2.var
. 换句话说,现在有两个名称为mod1.var
和mod2.var
。 They are the same at first, but when you reassign mod1.var
, mod2.var
still points to the same thing. 它们起初是相同的,但是当你重新分配mod1.var
, mod2.var
仍指向同一个东西。
What you want to do is just: 你想要做的只是:
import mod2
Then access and assign the variable as mod2.var
. 然后访问并将变量指定为mod2.var
。
It's important to note that global variables in Python are not truly global. 值得注意的是,Python中的全局变量并不是真正的全局变量。 They are global only to the module they're declared in. To access global variables inside another module, you use the module.variable
syntax. 它们仅对它们声明的模块是全局的。要访问另一个模块中的全局变量,可以使用module.variable
语法。 The global
statement can be used inside a function to allow a module-global name to be assigned to (without it, assigning to a variable makes it a local variable in that function). 可以在函数内部使用global
语句以允许分配模块全局名称(没有它,分配给变量使其成为该函数中的局部变量)。 It has no other effect. 它没有其他影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.