0

我正在尝试实现一个因子图。我想从一个单独的文件中读取因子函数。不幸的是,当我从一个文件中读取一个函数只是为了测试时,我得到了错误:

    eval(lines[0])(1,2,3)
  File "<string>", line 1
    def f(x0,x1,x2):
      ^
SyntaxError: invalid syntax

我的代码如下:

class Node:
    def __init__(self,name,graph):
        self.name = name
        self.graph = graph
        self.neighbourFactors=[];
class Factor:
    def __init__(self,name,neighbours,graph):
        self.name = name
        self.value = 1
        self.graph = graph
        self.neighbourNodes=[];
class Graph:
  def __init__(self,factorNumber,nodeNumber,factorNeighboursList):
    self.factorNumber = factorNumber
    self.factors=[Factor(i,factorNeighboursList[i],self) for i in range(factorNumber)]
    self.nodes=[Node(i,self) for i in range(nodeNumber)]
    factorNumber=0;
    for neighbourNodes in factorNeighboursList:
        for i in range(len(neighbourNodes)):       
            self.factors[factorNumber].neighbourNodes.append(self.nodes[int(neighbourNodes[i])]);
            self.nodes[int(neighbourNodes[i])].neighbourFactors.append(self.factors[factorNumber])
        factorNumber+=1;
def makeGraph(factorNumber,nodeNumber):
    factorNeighboursList=[]*factorNumber
    f = open('factorNeighboursInput.txt', 'r')        
    for line in f:
        factorNeighboursList.append(line.split())
    g=Graph(factorNumber,nodeNumber,factorNeighboursList)
    return g
factorNumber=input('Please specify number of Factors:')
nodeNumber=input('Please specify number of Nodes:')
g=makeGraph(factorNumber,nodeNumber)
f = open('factorFunctionInput.txt', 'r')        
lines=f.read().split(';')
print lines
eval(lines[0])(1,2,3)

我单独的函数输入文件是:

def f(x0,x1,x2):
    return x0*x1*x2
;
def f(x1):
    return x1+1
;
def f(x2):
    return x2
;
def f(x3):
    return x3+2
;
4

1 回答 1

1

我认为在使用多行 eval 函数调用 eval 的情况下,它会失败。您应该使用 eg.exec 而不是 eval:解决方案

此外,我认为您必须调用函数,定义似乎还不够:

    def f(x0,x1,x2):
       return x0*x1*x2

    f(x0,x1,x2)
于 2013-06-16T14:05:21.243 回答