0

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?

Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
Student
  • 287
  • 4
  • 9

4 Answers4

2

Try this:

class Graph( object ):
    def ReadGraph( file_name ):
        # do something
        pass

def ProcessGraph(file_name, verbose):
    g = Graph()
    return g.ReadGraph(file_name)
Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
1

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
1

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'.

staticmethod vs classmethod

Community
  • 1
  • 1
Peter Kelly
  • 14,253
  • 6
  • 54
  • 63
0

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
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71