one*_*ach 2 python global-variables
我想将变量全局变为2个以上的文件,以便在包含变量的文件中反映任何文件中的操作.
我在做的是:
b.py
import a
x = 0
def func1():
global x
x = 1
if __name__ == "__main__":
print x
func1()
print x
a.func2()
print x
Run Code Online (Sandbox Code Playgroud)
a.py
import b
def func2():
print b.x
b.x = 2
Run Code Online (Sandbox Code Playgroud)
我在这里搜索了线程,发现from a import *正在复制,import a否则.我希望上面的代码在执行时打印0 1 1 2(确定它应该在新行中),python b.py但它正在显示0 1 0 1
如何实现?
首先让我说我认为像这样的全局变量(使用全局关键字)是邪恶的.但重组它的一种方法是将您的全局变量放入SEPARATE模块中的类以避免循环导入.
a.py
from c import MyGlobals
def func2():
print MyGlobals.x
MyGlobals.x = 2
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
c.py
class MyGlobals(object):
x = 0
Run Code Online (Sandbox Code Playgroud)
OUTPUT
$ python b.py
0
1
1
2
Run Code Online (Sandbox Code Playgroud)