如何在不同的python文件之间交换变量



我有 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 中实现变量图而不是从 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'}

最新更新