Python从其他文件导入变量

标签 python function file variables import

我在同一目录中有 3 个文件:test1.py、test2.py 和 init.py。

在 test1.py 中我有这段代码:

def test_function():
    a = "aaa"

在 test2.py 中我有这段代码:

from test1 import *


def test_function2():
    print(a)


test_function2()

我可以将“test_function”(并调用该函数)导入 test2.py 但我不能在 test2.py 中使用变量“a”。

Error : Unresolved reference "a" .

我想知道是否可以在 test2.py 中使用“a”。

最佳答案

在 test1.py 中你可以有一个函数返回变量 a 的值

def get_a():
    return a

当你在 test2.py 中时,你可以调用 get_a()

因此在 test2.py 中执行此操作实质上是从 test1.py 中移动 a 的值。

from test1 import *

a = get_a()

def test_function2():
    print(a)


test_function2()

关于Python从其他文件导入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517260/

相关文章:

python - 在当前类中循环调用另一个类函数

javascript - JS : Higher Order Function Problem; Accept Array and Callback Function --> don't understand

python - 如何正确地通过 python-urllib2 通过 HTTP 下载文件?

c++ - 在 C++ 中使用 Dos 命令时使用 GetLastError

python - Subprocess.Popen 在解释器、可执行脚本中的行为不同

python - 从 Databricks 上的代码重新启动 Python 解释器?

c++ - 在这种情况下如何释放内存?

php - 无法将文件上传到网络服务器

python - 从矩阵到单词列表

python - 通过从列表中获取元素来更改 xpath