问题描述
我在同一目录中有3个文件:test1.py,test2.py和 init .py.
I have 3 files in the same directory : test1.py , test2.py and init.py.
在test1.py中,我有以下代码:
In test1.py I have this code:
def test_function():
a = "aaa"
在test2.py中,我有以下代码:
In test2.py I have this code:
from test1 import *
def test_function2():
print(a)
test_function2()
我可以将"test_function"(并调用该函数)导入到test2.py中,但是我不能在test2.py中使用变量"a".
I can import "test_function" (and call the function) into test2.py but i cannot use the variable "a" in test2.py .
我想知道是否可以在test2.py中使用"a".
I would like to know if it possible to use "a" inside test2.py .
推荐答案
在test1.py中,您可以使用一个函数来返回变量a的值
In test1.py you could have a function that returns the value of the variable a
def get_a():
return a
当您进入test2.py时,您可以致电get_a()
.
And when you're in test2.py you can call get_a()
.
因此,在test2.py中执行此操作实际上是将其移到test1.py中的a值之上.
So in test2.py do this to essentially move over the value of a from test1.py.
from test1 import *
a = get_a()
def test_function2():
print(a)
test_function2()
这篇关于Python从其他文件导入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!