我在同一目录中有 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/