简体   繁体   English

在Python中的类中调用函数

[英]Calling functions in a class in Python

Suppose that I have the following in a single .py file: 假设我在单个.py文件中具有以下内容:

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

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

where ProcessGraph is a driver class. 其中ProcessGraph是驱动程序类。 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. ReadGraphGraph类的名称空间中,这就是为什么您不能将其称为高级函数的原因。 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. @classmethod装饰器将使您ReadGraph在不创建类实例的情况下在类上调用ReadGraph

Just decorate them with @staticmethod 只需用@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'. 输出'hello'。

staticmethod vs classmethod 静态方法与类方法

create a instance of Graph class. 创建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