我遇到了一个我不明白的情况。我有三个文件:
one.py(可运行):
import two
import three
three.init()
two.show()
二.py:
import three
def show():
print(three.test)
三.py:
test = 0
def init():
global test
test = 1
如我所料,结果是 1。现在让我们修改two.py:
from three import test
def show():
print(test)
结果是 0。为什么?
最佳答案
一切都与范围有关。 如果您按如下方式更改 one.py,您会看得更清楚。
import three
from three import test
three.init()
print(test)
print(three.test)
它将打印:
0 <== test was imported before init()
1 <== three.test fetches the current value
当您只导入变量时,它会创建一个局部变量,它是一个不可变的整数。
但是如果你像下面这样改变导入语句的顺序,你会得到不同的结果:
import three
three.init()
print(three.test)
from three import test
print(test)
它将打印:
1 <== three.test fetches the current value
1 <== test was imported after init()
关于python - python导入全局变量的两种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46685712/