Reputation: 297
Suppose that I have the following in a single .py
file:
class Graph( object ):
def ReadGraph( file_name ):
def ProcessGraph(file_name, verbose):
g=ReadGraph(file_name)
where ProcessGraph
is a driver class. When I type
ProcessGraph('testcase.txt', verbose=True)
I get this error
NameError: global name 'ReadGraph' is not defined
Could someone explain how to fix this error?
Upvotes: 0
Views: 80
Reputation: 46533
ReadGraph
is in the namespace of the Graph
class, which is why you can't call it as a high-level function. Try this:
class Graph(object):
@classmethod
def ReadGraph(cls, file_name):
# Something
def ProcessGraph(file_name, verbose):
g=Graph.ReadGraph(file_name)
The @classmethod
decorator will let you call ReadGraph
on a class without creating a class instance.
Upvotes: 1
Reputation: 14391
Just decorate them with @staticmethod
class Graph( object ):
@staticmethod
def ReadGraph( file_name ):
print 'read graph'
@staticmethod
def ProcessGraph(file_name, verbose):
g=ReadGraph(file_name)
if __name__=="__main__":
Graph.ProcessGraph('f', 't')
Outputs 'hello'.
Upvotes: 1
Reputation: 9828
create a instance of Graph class.
class Graph(object): def ReadGraph(file_name): pass
def ProcessGraph(file_name, verbose): g = Graph() out = g.ReaGraph(file_name) print out
Upvotes: 0
Reputation: 4317
Try this:
class Graph( object ):
def ReadGraph( file_name ):
# do something
pass
def ProcessGraph(file_name, verbose):
g = Graph()
return g.ReadGraph(file_name)
Upvotes: 2