Reputation: 297
I have two modules called Dfs and Graph. In my Graph module, I have a class Graph and a method called ReadGraph. In my Dfs module, I have a method that calls on ReadGraph but I get the following error message when I type: Dfs.ProcessGraph(testcase.txt,verbose=True)
Error message: NameError: name 'testcase' is not defined
Could someone explain how to fix this?
Thanks.
From my Dfs.py module:
import sys
from Graph import *
class Dfs( object ):
def ProcessGraph(file_name, verbose):
g=ReadGraph(file_name)
From my Graph.py module:
class Graph( object ):
def ReadGraph( file_name ):
Upvotes: 0
Views: 180
Reputation: 814
your code should be : Dfs.ProcessGraph('testcase.txt',verbose=True)
and not Dfs.ProcessGraph(testcase.txt,verbose=True)
'testcase.txt' # is a string and should be between quotes
also check if it is in the same directory where your code live else point to it
plus in DFs you should instantiate Graph :
from Graph.Graph import *
g = Graph()
grf = g.ReadGraph('filename')
EDIT: to be more precise
in Graph module:
class Graph(object):
def __init__(self):
pass # for the example now
def read_graph(self, file_name):
return file_name
in Dfs Module:
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)
Upvotes: 0
Reputation: 122024
You have multiple problems here:
from Graph import *
(which is bad practice to start with), you bring Graph
into your name space. However, ReadGraph
is inside Graph
, so to access it you need Graph.ReadGraph
. Dfs.ProcessGraph(testcase.txt,verbose=True)
. The first argument is interpreted as "pass the txt
attribute of the object referenced by name testcase
, which doesn't exist. Instead, you mean "testcase.txt"
(quoted to make it a string).TypeError: unbound method ProcessGraph() must be called with Dfs instance as first argument (got str instance instead)
. When you call an instance method, the first argument, self
by convention, is the instance itself. You have two choices; either a) make e.g. ProcessGraph
a @staticmethod
, and access it Graph.ReadGraph
; or b) move it outside the class, then you can access it directly like you tried to in the first place. As you don't seem to have any class or instance attributes, it's not clear why you are bothering with the classes at all. What it should probably look like:
import sys
from Graph import read_graph
def process_graph(file_name, verbose):
g = read_graph(file_name)
Graph.py
module (note absence of class Graph
):
def read_graph(file_name):
...
(Generally, I suggest you read PEP 8).
Upvotes: 1
Reputation: 3247
Remove your class declaration from Graph.py. When you import all from a file you get all top level objects. In this case it's the Graph
class itself, not its methods.
Also you need to pass string 'testcase.txt'
not testcase.txt
.
Upvotes: 1