繁体   English   中英

在Python中的类中调用函数

[英]Calling functions in a class in 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

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

尝试这个:

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

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

ReadGraphGraph类的名称空间中,这就是为什么您不能将其称为高级函数的原因。 尝试这个:

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

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

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

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

输出'hello'。

静态方法与类方法

创建Graph类的实例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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