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

时间:2019-04-16 09:16:30

标签: python python-3.x file python-import

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

如果我按照here创建了一个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'

1 个答案:

答案 0 :(得分:0)

只需避免在导入时构造的全局变量。

下面,我使用函数作为访问器来延迟符号的解析:

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'}