Python使用其他模块中的方法

2024-09-28 22:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模块叫做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 ):

Tags: 模块文件方法namepyimport消息verbose
3条回答

从中删除类声明图形.py. 从文件导入所有对象时,会得到所有顶级对象。在本例中,它是Graph类本身,而不是它的方法。你知道吗

您还需要传递字符串'testcase.txt',而不是testcase.txt。你知道吗

这里有多个问题:

  1. 如果你from Graph import *(这是一个糟糕的开始),你会把Graph带入你的名字空间。但是,ReadGraphGraph内,所以要访问它,您需要Graph.ReadGraph。你知道吗
  2. 完成之后,您尝试调用Dfs.ProcessGraph(testcase.txt,verbose=True)。第一个参数被解释为“传递名称testcase引用的对象的txt属性,该属性不存在。相反,您指的是"testcase.txt"(加引号使其成为字符串)。你知道吗
  3. 完成所有这些之后,您将得到例如TypeError: unbound method ProcessGraph() must be called with Dfs instance as first argument (got str instance instead)。调用实例方法时,第一个参数self按约定是实例本身。您有两种选择:要么a)使例如ProcessGrapha @staticmethod,并访问它Graph.ReadGraph;要么b)将它移到类之外,然后您可以像最初尝试的那样直接访问它。因为您似乎没有任何类或实例属性,所以不清楚为什么要处理这些类。你知道吗

它应该是什么样子的:

import sys 

from Graph import read_graph

def process_graph(file_name, verbose):
  g = read_graph(file_name)

Graph.py模块(注意缺少class Graph):

def read_graph(file_name):
    ...

(一般来说,我建议你读PEP 8)。你知道吗

您的代码应该是:Dfs.ProcessGraph('testcase.txt',verbose=True) 而不是Dfs.ProcessGraph(testcase.txt,verbose=True)

'testcase.txt' # is a string and should be between quotes

还要检查它是否在代码所在的同一目录中,否则请指向它

另外,在DFs中,您应该实例化图形:

from Graph.Graph import *
g = Graph()
grf = g.ReadGraph('filename')

编辑:更准确地说

在图形模块中:

class Graph(object):
    def __init__(self):
        pass # for the example now

    def read_graph(self, file_name):
        return file_name

在Dfs模块中:

from Graph import *
class Dfs(object):
    def __init__(self):
        pass # for the example now

    def ProcessGraph(file_name, verbose):
        g  = Graph()
        file_name = Graph.read_graph(file_name)

相关问题 更多 >