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?

2
  • ReadGraph() is a method of the Graph class. You need an instance of Graph in order to call it. Commented Apr 25, 2014 at 8:57
  • I doubt very much you need classes here at all. Python is not Java. Commented Apr 25, 2014 at 9:20

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.