我遇到了一个我不明白的情况。我有三个文件:以两种方式在python中导入全局变量
one.py(可运行):
import two
import three
three.init()
two.show()
two.py:
import three
def show():
print(three.test)
three.py:
test = 0
def init():
global test
test = 1
的结果是1,如我所料。现在让我们来修改two.py:
from three import test
def show():
print(test)
结果是0.为什么?
因为这'三个进口test'的..在第二个two.py中,你只导入'test',在three.py中等于'0'。 –
长话短说:在第二种情况下,'test'成为'two.py'的本地,所以重新绑定'three.test'不会影响'two.test'(这是两个不同的名字)。有关详细说明,请阅读以下内容:https://nedbatchelder.com/text/names.html –