[英]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中,僅在函數內部引用的變量是隱式全局的。 如果在函數體內任何位置為變量分配了值,除非明確聲明為全局變量,否則將假定該變量為局部變量。
所以使變量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.