2017-10-11 80 views
3

我遇到了一个我不明白的情况。我有三个文件:以两种方式在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.为什么?

+1

因为这'三个进口test'的..在第二个two.py中,你只导入'test',在three.py中等于'0'。 –

+3

长话短说:在第二种情况下,'test'成为'two.py'的本地,所以重新绑定'three.test'不会影响'two.test'(这是两个不同的名字)。有关详细说明,请阅读以下内容:https://nedbatchelder.com/text/names.html –

回答

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语句的顺序像下面你会得到不同的结果:

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() 
+1

“只导入变量时,它将以不同方式编译。” =>这与编译完全没有关系,所有这些都是在运行时发生的。 –

+0

感谢您的评论,我已修复该声明。 – scriptmonster