从静态方法调用非静态方法

时间:2012-08-02 11:00:24

标签: python plone

我有一个类和portal_type Person,其中有两个方法:

class Person(BaseContent):
    def print_all(self):
        catalog = getToolByName(self, "portal_catalog")
        results = catalog(portal_type = 'Person')
        final_result = ''
        for result in results:
            final_result += result.getObject().print_person()
        return final_result

    def print_person(self):
        return self.name

但我意识到print_all与任何对象都没有关联,因此它应该是静态方法。我想要做的是获取该人的所有实例并调用print_person()。但问题是:我应该在目录中写什么,因为在我创建print_all方法静态方法之后没有自我对象。例如,现在我不能写

catalog = getToolByName(self, "portal_catalog")

我想要类似的东西:

@staticmethod
def print_all():
    instance = Person()
    catalog = getToolByName(instance, "portal_catalog")
    .
    .
    .

但它在'invalid syntax'给我instance = Person()错误!我希望我的问题很清楚,任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以将self替换为context,如下所示:

# this is needed only if you don't have a context to pass
from zope.app.component import hooks

def print_all(context=None):
    if context is None:
        context = hooks.getSite()
    catalog = getToolByName(context, "portal_catalog")
    results = catalog(portal_type = 'Person')
    final_result = ''
    for result in results:
        final_result += result.getObject().print_person()
    return final_result