[英]How to exchange variables between different python files?
我在同一目錄中有2個python文件file1.py和file2.py.
#file1.py
import file2 as f2
graph={ 0: [1,2],
1: [0,3,2,4],
2: [0,4,3,1],
3: [1,2,5],
4: [2,1,5],
5: [4,3]
}
def function1(graph):
print(f2.C1)
另一個文件是
#file2.py
import file1 as f1
graph=f1.graph
def function2(graph):
#Perform some operation on graph to return a dictionary C
return C
C1=function2(graph)
當我運行file1時,我收到一個錯誤
module 'file2' has no attribute 'C1'
當我運行file2並嘗試檢查C1變量的值時,我收到一個錯誤:
module 'file1' has no attribute 'graph'
如何正確導入這些文件以便適當地交換文件之間的值?
請注意,當我直接在file2中實現變量graph而不是從file1中獲取時,它可以很好地工作,但是當在文件之間交換變量時,它會開始產生問題。
編輯:
我添加了更精煉的代碼版本來簡化問題。
#file1
import file2 as f2
def fun1(graph):
C=[None]*20
for i in range(20):
# Some algorithm to generate the subgraphs s=[s1,s2,...,s20]
C[i]=f2.fun2(s[i])
print(C[i])
graph={ 0: [1,2],
1: [0,3,2,4],
2: [0,4,3,1],
3: [1,2,5],
4: [2,1,5],
5: [4,3]
}
def getGraph():
return graph
fun1(graph)
其他文件file2.py
import file1 as f1
graph_local=f1.getGraph()
#Some operations on graph_local to generate another graph 'graph1' of same "type" as graph_local
def fun2(graph1):
#Perform some operation on graph1 to return a dictionary C
return C
如果我創建這里提到的test.py,
#test.py
from file1 import fun1
fun1(None)
當我運行test.py或file2.py時,錯誤是
module 'file1' has no attribute 'getGraph'
而當我運行file1.py時,
module 'file2' has no attribute 'C'
只需避免導入時構造的全局變量。
下面我使用了函數作為延遲符號分辨率的訪問器:
test.py:
from file1 import function1
function1(None)
file1.py
import file2
# I have retained graph here
graph={ 0: [1,2],
1: [0,3,2,4],
2: [0,4,3,1],
3: [1,2,5],
4: [2,1,5],
5: [4,3]
}
def getGraph():
return graph
def function1(graph):
print(file2.getC1())
file2.py
import file1 as f1
# graph=f1.getGraph()
def function2(graph):
graph[6]='Added more'
#Perform some operation on graph to return a dictionary C
return graph
def getC1():
return function2(f1.getGraph())
當我運行test.py時,我得到了這個輸出:
{0: [1, 2], 1: [0, 3, 2, 4], 2: [0, 4, 3, 1], 3: [1, 2, 5], 4: [2, 1, 5], 5: [4, 3], 6: 'Added more'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.