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

问题描述 投票:0回答:1

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

如果我按照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'
python python-3.x file python-import
1个回答
0
投票

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

下面我使用了函数作为延迟符号分辨率的访问器:

test.朋友:

from file1 import function1

function1(None)

file1.朋友

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.朋友

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'}
© www.soinside.com 2019 - 2024. All rights reserved.