Student
Student

Reputation: 297

Calling functions in a class in Python

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

Answers (4)

vaultah
vaultah

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

Peter Kelly
Peter Kelly

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

staticmethod vs classmethod

Upvotes: 1

Prashant Gaur
Prashant Gaur

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

Roberto Reale
Roberto Reale

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

Related Questions