Python:在其中的模块和类之间共享全局变量 [英] Python: Sharing global variables between modules and classes therein
问题描述
我知道可以在Python中跨模块共享一个全局变量。但是,我想知道这是可能的程度,为什么。例如,
global_mod.py
x =无$ b b
$ mid_access_mod.py c $ c> from global_mod import *
class delta:
def __init __(self):
print x
$ b bot_modif_mod.py import mid_access_mod
import global_mod
class mew:
def __init __(self):
global_mod.x = 5
def main():
m = mew()
d = mid_access_mod.delta()
即使所有模块共享全局变量x。为什么会这样?看起来像x在mid_access_mod.py被mew()分配到bot_modif_mod.py之前被评估过。 这会发生因为你正在使用不可变的值(ints和None),并且导入变量就像是按值传递东西,而不是通过引用传递东西。
如果您制作了global_mod.xa列表,并操纵它的第一个元素,它就会像你期望的那样工作。
当你从global_mod import x 执行时,您正在模块中创建名称
x
,其值与 x
在 global_mod中的值相同
。对于像函数和类这样的东西,这可以像预期的那样工作,因为人们(通常)不会在以后重新分配这些名称。
import global_mod
,然后使用 global_mod.x
,您将避免该问题。您在模块中定义的名称将是 global_mod
,它总是指您想要的模块,然后使用属性访问获取 x 会为您带来最新的 x
。
I know that it's possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example,
global_mod.py
x = None
mid_access_mod.py
from global_mod import *
class delta:
def __init__(self):
print x
bot_modif_mod.py
import mid_access_mod
import global_mod
class mew:
def __init__(self):
global_mod.x = 5
def main():
m = mew()
d = mid_access_mod.delta()
This prints None, even though all the modules are sharing the global variable x. Why is this the case? It seems like x is evaluated at mid_access_mod.py before it is assigned in bot_modif_mod.py by mew().
解决方案 This happens because you are using immutable values (ints and None), and importing variables is like passing things by value, not passing things by reference.
If you made global_mod.x a list, and manipulated its first element, it would work as you expect.
When you do from global_mod import x
, you are creating a name x
in your module with the same value as x
has in global_mod
. For things like functions and classes, this works as you would expect, because people (generally) don't re-assign to those names later.
As Alex points out, if you use import global_mod
, and then global_mod.x
, you will avoid the problem. The name you define in your module will be global_mod
, which always refers to the module you want, and then using attribute access to get at x
will get you the latest value of x
.
这篇关于Python:在其中的模块和类之间共享全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!