Python 无法调用方法,除非其全局值来自类
您好,我是迪斯科新手,并将现有代码集成到其中。Disco是否能够将map/reduce函数作为类内函数而不是全局函数调用?下面的代码可能会解释得更清楚Python 无法调用方法,除非其全局值来自类,python,disco,Python,Disco,您好,我是迪斯科新手,并将现有代码集成到其中。Disco是否能够将map/reduce函数作为类内函数而不是全局函数调用?下面的代码可能会解释得更清楚 class Segmenter(object): def map_fun(line, params): .... def reduce_fun(iter, params): .... def disco_mp(self): job = Job().run(input=["ra
class Segmenter(object):
def map_fun(line, params):
....
def reduce_fun(iter, params):
....
def disco_mp(self):
job = Job().run(input=["raw://word_to_segment_......"],
map=map_fun,
reduce=reduce_fun)
...
执行的结果是
NameError: global name 'map_fun' is not defined
但如果我改变map_-fun,将其简化为全局函数,它会像预期的那样正常工作。
然而,我仍然需要找到一种方法使它作为类函数工作,有什么方法可以
怎么办
谢谢
钱德勒看起来你想使用
self.map\u-fun
和self.reduce\u-fun
。在Python中,对象的方法不能通过它们的裸名称访问;您必须使用self
。您还需要为这些方法提供一个self
参数。您应该阅读本书以熟悉Python中类和方法的基础知识
(还有,为什么问题的标题与实际问题无关?您需要静态方法,您可以使用decorator:
class Segmenter(Job):
map = staticmethod(map_fun)
reduce = staticmethod(reduce_fun)
@staticmethod
def map_fun(line, params):
....
@staticmethod
def reduce_fun(iter, params):
....
def disco_mp(self):
job = self.run(input=["raw://word_to_segment_......"])
请注意,在map_-fun和reduce_-fun中,您将无法访问
self
,这就是params
存在的原因。还要注意的是,Job.run
现在是self.run
和Segmenter
扩展了Job
问题的标题与实际问题有什么关系?类的方法应该将self
作为第一个参数。您需要编辑问题,显示您的新代码和新错误。是的,我将代码更改为map=self.map\u-fun,
reduce=self.reduce\u-fun)
错误变成这样。ModUtilitImportError:没有名为Segmenter的模块:找不到在map\u fun中定义的模块。也许是打字错误。有关如何包含模块的详细信息,请参阅所需_modules参数的文档。