在python中将变量全局变为多个文件 [英] make variable global to multiple files in python
问题描述
我想将一个变量全局变为2个以上的文件,以便任何文件中的操作反映在包含变量的文件中。
我正在做的是:
b.py
import a
$ bx = 0
def func1():
全局x
x = 1
if __name__ ==__main__:
print x
func1()
print x
a.func2()
print x
a.py
进口b
def func2():
print bx
bx = 2
我有在这里搜索线程并从导入中找到 *
正在复制,否则导入
。我期望上面的代码在执行 python b.py $ c $>时打印
0 1 1 2
(确保它应该换行) c>但它显示 0 1 0 1
如何实现它?
$ b $让我先说我认为像这样的全局变量(使用全局关键字)是邪恶的。但重组它的一种方法是将全局变量放入SEPARATE模块的类中,以避免循环导入。
a.py 从$ import MyGlobals
def func2():
print MyGlobals。
x
MyGlobals.x = 2
b.py
从c import a
MyGlobals
$ b def func1():
MyGlobals.x = 1
if __name__ ==__main__:
print MyGlobals.x
func1()
print MyGlobals.x
a.func2()
print MyGlobals.x
c.py
class MyGlobals(object):
x = 0
OUTPUT
$ python b.py
0
1
1
2
I want to make a variable global to more than 2 files so that operating in any file reflects in the file containing the variable.
what I am doing is:
b.py
import a
x = 0
def func1():
global x
x = 1
if __name__ == "__main__":
print x
func1()
print x
a.func2()
print x
a.py
import b
def func2():
print b.x
b.x = 2
I have searched for threads here and find from a import *
is making copies and import a
is otherwise. I expect the code above to print 0 1 1 2
(sure it should be in new lines) when execute python b.py
but it's showing 0 1 0 1
How does one implement that?
Let me start by saying that I think globals like this (using the global keyword) are evil. But one way to restructure it is to put your globals into a class in a SEPARATE module to avoid circular imports.
a.py
from c import MyGlobals
def func2():
print MyGlobals.x
MyGlobals.x = 2
b.py
import a
from c import MyGlobals
def func1():
MyGlobals.x = 1
if __name__ == "__main__":
print MyGlobals.x
func1()
print MyGlobals.x
a.func2()
print MyGlobals.x
c.py
class MyGlobals(object):
x = 0
OUTPUT
$ python b.py
0
1
1
2
这篇关于在python中将变量全局变为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!