我有两个模块叫做Dfs和Graph。 在我的Graph模块中,我有一个类图和一个名为ReadGraph的方法。 在我的Dfs模块中,我有一个调用ReadGraph的方法,但在键入时会收到以下错误消息:Dfs.ProcessGraph文件(testcase.txt文件,verbose=真)
错误消息: NameError:未定义名称“testcase”
有人能解释一下怎么解决这个问题吗?你知道吗
谢谢。你知道吗
从我的Dfs.py文件模块:
import sys
from Graph import *
class Dfs( object ):
def ProcessGraph(file_name, verbose):
g=ReadGraph(file_name)
从我的图形.py模块:
class Graph( object ):
def ReadGraph( file_name ):
从中删除类声明图形.py. 从文件导入所有对象时,会得到所有顶级对象。在本例中,它是
Graph
类本身,而不是它的方法。你知道吗您还需要传递字符串
'testcase.txt'
,而不是testcase.txt
。你知道吗这里有多个问题:
from Graph import *
(这是一个糟糕的开始),你会把Graph
带入你的名字空间。但是,ReadGraph
在Graph
内,所以要访问它,您需要Graph.ReadGraph
。你知道吗Dfs.ProcessGraph(testcase.txt,verbose=True)
。第一个参数被解释为“传递名称testcase
引用的对象的txt
属性,该属性不存在。相反,您指的是"testcase.txt"
(加引号使其成为字符串)。你知道吗TypeError: unbound method ProcessGraph() must be called with Dfs instance as first argument (got str instance instead)
。调用实例方法时,第一个参数self
按约定是实例本身。您有两种选择:要么a)使例如ProcessGraph
a@staticmethod
,并访问它Graph.ReadGraph
;要么b)将它移到类之外,然后您可以像最初尝试的那样直接访问它。因为您似乎没有任何类或实例属性,所以不清楚为什么要处理这些类。你知道吗它应该是什么样子的:
Graph.py
模块(注意缺少class Graph
):(一般来说,我建议你读PEP 8)。你知道吗
您的代码应该是:
Dfs.ProcessGraph('testcase.txt',verbose=True)
而不是Dfs.ProcessGraph(testcase.txt,verbose=True)
还要检查它是否在代码所在的同一目录中,否则请指向它
另外,在DFs中,您应该实例化图形:
编辑:更准确地说
在图形模块中:
在Dfs模块中:
相关问题 更多 >
编程相关推荐