简体   繁体   中英

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?

Try this:

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

def ProcessGraph(file_name, verbose):
    g = Graph()
    return g.ReadGraph(file_name)

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM