以两种方式在python中导入全局变量

时间:2017-10-11 10:20:03

标签: python python-3.x

我遇到了一个我不明白的情况。我有三个文件:

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.为什么?

1 个答案:

答案 0 :(得分:1)

一切都与范围有关。 如果您按照以下方式更改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()