繁体   English   中英

Python从其他文件导入变量

[英]Python importing variables from other file

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

在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中局部和全局变量的规则是什么?¶

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

Test1.py

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

Test2.py

import test1


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


test_function2()

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

test1.py的代码就是这个。

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

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

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

这将允许您致电测试一个H

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

谢谢 ! :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM