在Python中调用类中的函数

时间:2014-04-25 08:55:21

标签: python

假设我在单个.py文件中包含以下内容:

class Graph( object ):
    def ReadGraph( file_name ):

def ProcessGraph(file_name, verbose):
    g=ReadGraph(file_name)

其中ProcessGraph是驱动程序类。当我输入

ProcessGraph('testcase.txt', verbose=True)

我收到此错误

NameError: global name 'ReadGraph' is not defined

有人可以解释如何修复此错误吗?

4 个答案:

答案 0 :(得分:2)

试试这个:

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

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

答案 1 :(得分:1)

ReadGraph位于Graph类的命名空间中,这就是为什么你不能把它称为高级函数。试试这个:

class Graph(object):
     @classmethod
     def ReadGraph(cls, file_name):
         # Something

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

@classmethod装饰器可让您在不创建类实例的情况下调用类ReadGraph

答案 2 :(得分:1)

用@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')

输出'你好'。

staticmethod vs classmethod

答案 3 :(得分:0)

创建Graph类的实例。

class Graph(object):
    def ReadGraph(file_name):
        pass
def ProcessGraph(file_name, verbose):
    g = Graph()
    out = g.ReaGraph(file_name)
    print out