如何在Python 3中的方法装饰器中调用super?

时间:2014-09-18 20:13:49

标签: python python-3.x decorator super python-decorators

如何填写???

def ensure_finished(iterator):
    try:
        next(iterator)
    except StopIteration:
        return
    else:
        raise RuntimeError


def derived_generator(method):
    def new_method(self, *args, **kwargs):
        x = method(self, *args, **kwargs)
        y = getattr(super(???, self), method.__name__)\
            (*args, **kwargs)

        for a, b in zip(x, y):
            assert a is None and b is None
            yield

        ensure_finished(x)
        ensure_finished(y)

    return new_method

1 个答案:

答案 0 :(得分:-1)

编辑:由于评论中提到的原因,这不起作用。我将此留在这里,以便下一个尝试回答的人不会做同样的事情(直到真正的答案出现)。

您应该使用type(self)

示例我简化了你的代码,但本质仍应该在那里

def derived_generator(method):
    def new_method(self, *args, **kwargs):
        x = method(self, *args, **kwargs)
        y = getattr(super(type(self), self), method.__name__)\
            (*args, **kwargs)

        for a, b in zip(y, x):
            yield a, b

    return new_method

class BaseClass(object):
    def iterator(self):
        return [1, 2, 3]

class ChildClass(BaseClass):
    @derived_generator
    def iterator(self):
        return [4, 5, 6]

a = ChildClass()
for x in a.iterator():
    print(x)