Python从其他文件导入变量

时间:2019-06-09 18:21:20

标签: 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”。

  

错误:未解决的引用“ a”。

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

6 个答案:

答案 0 :(得分:3)

在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()

答案 1 :(得分:1)

What are the rules for local and global variables in Python?¶

  

在Python中,仅在函数内部引用的变量是隐式全局的。 如果在函数体内任何位置为变量分配了值,除非明确声明为全局变量,否则将假定该变量为局部变量。

因此,将变量a设置为全局变量,然后在test_function()模块中调用test1,以便在加载模块时将a设置为全局变量

test1.py

def test_function():
  global a
  a = "aaa"

test_function() 

test2.py

from test1 import *

def test_function2():
  print(a)


test_function2()

答案 2 :(得分:1)

Test1.py

def test_function():
    a = "aaa"
    return a

Test2.py

import test1


def test_function2():
    print(test1.test_function())


test_function2()

答案 3 :(得分:1)

a仅在test_function()的范围内定义。您必须在函数外部定义它,并使用global关键字对其进行访问。看起来像这样:

test1.py

a = ""
def test_function():
    global a
    a = "aaa"

test2.py

import test1

def test_function2():
    print(test1.a)

test1.test_function()
test_function2()

答案 4 :(得分:0)

test1.py的代码就是这个。

def H():
    global a
    a = "aaa"
H()

和test2.py的代码就是这个。

import test1 as o
global a
o.H()
print(o.a)

这将允许您调用测试一个H

答案 5 :(得分:0)

您的代码运行完美(在test1_function外部定义了“ a”),能够打印“ a”。因此,请尝试以下操作: 1.确保它是test1中的全局变量。 2.在交互式会话中导入test1并找出错误。 3.仔细检查环境设置。

谢谢! :)

相关问题