[英]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)
ReadGraph
在Graph
類的名稱空間中,這就是為什么您不能將其稱為高級函數的原因。 嘗試這個:
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.