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

标签 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

最佳答案

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

您应该使用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)

关于python - 如何在 Python 3 的方法装饰器中调用 super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921537/

相关文章:

python - 如何为不同的实现提取学习到的 ML 模型?

python - 转换 Dataframe 列以解决 TypeError Cannot be hashed

javascript - javascript装饰器中的 `target`是什么

python - google app engine - ndb 查询只获取 python 中的几列

python - 是否可以将 Python 中的 HTMLUnit 驱动程序与 Selenium 一起使用?

python - PyQt5 QStandardItem 存储旧父项

python - @unique 装饰器在 python 中有什么作用?

django - 为什么需要用@method_decorator装饰login_required装饰器

python - 在安装 Django 期间,为什么我不断收到 ImportError : No module named django?

Python:用另一个字符替换转义引号