python - python导入全局变量的两种方式

标签 python python-3.x

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

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/

相关文章:

python - Nuitka standalone 并不是真正独立的

python - 如何为缺少数据的移动对象坐标生成插值器?

python - 如何使用 Kubernetes Python 客户端连接到 Google Kubernetes 引擎

python - 如何提取嵌套列表中字符串的最小位置

python - 从 Pandas 中的两个不同行解析日期

Python future 组合

c++ - Python 3.6 pyrfc 导入错误

python - 在 Python 3 中检查多个整数

python - 如何在不使用函数的情况下在 python 中打印名称的反转?

Python Bot 使用自定义表情符号