如何在Python 3中的方法装饰器中调用super? [英] How do I call super in a method decorator in Python 3?

查看:114
本文介绍了如何在Python 3中的方法装饰器中调用super?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何填写 ???

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


推荐答案

EDIT:评论中提到的原因。我将其留在此处,以便下一个尝试回答的人不会做同样的事情(直到出现真正的答案)。

EDIT : This does not work for the reasons mentioned in the comments. I'll leave this here so that the next guy trying to answer doesn't do the same thing (until the real answer shows up).

您应该使用 type(self)

示例我简化了代码,但本质上还是在那里

Example I simplified your code a bit, but the essence should still be in there

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)

这篇关于如何在Python 3中的方法装饰器中调用super?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆