无法从类中调用方法,除非它是全局的.

2024-05-18 11:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我是新来的迪斯科和整合现有的代码。Disco是否能够调用map/reduce函数作为类中的函数而不是全局函数?下面的代码可以更清楚地解释。在

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)
        ...

执行的结果是

^{pr2}$

但如果我改变map_fun,将其减为全局函数,它会像预期的那样工作得很好。 但是我仍然需要找到一种方法使它作为类函数工作,有什么方法可以 去做吗?在

谢谢

钱德勒


Tags: 方法函数代码mapreduceobjectdefline
2条回答

看起来您想使用self.map_funself.reduce_fun。在Python中,对象的方法不能通过它们的裸名称来访问;必须使用self。您还需要为这些方法提供一个self参数。您应该阅读the Python tutorial,以熟悉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\u fun和reduce\u fun中访问self,这就是{}存在的原因。还要注意,Job.run现在是self.run,而{}扩展了{}。在

相关问题 更多 >