python - 如何在基类的函数上使用装饰器,并在继承基类时让装饰器作用于该函数

标签 python class inheritance python-decorators

我有一个基类 Example 和一个抽象方法 example。我想在 example 函数上添加另一个装饰器,我在下面做了 - 装饰器是 @foo

当我使用这个 Example 基类创建新类时,我创建了一个合适的 example 函数,@foo 应该做什么,不'结束工作。

我认为问题是当我在新类上创建 example 函数时它被“覆盖”了。

from abc import ABCMeta, abstractmethod

class Example(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        self.num = 0

    @abstractmethod
    @foo
    def example(self, output):
        pass

class ExampleSum(Example):
    def example(self, output):
        self.num = self.num + output

有什么指导吗?基本上我希望 @foo 行为在 ExampleSumexample 函数中而不显式编码。

最佳答案

I believe the issue is that it is being 'overridden' when I create the example function on a new class.

你是绝对正确的:装饰方法被覆盖。但是如果你只对 example 的“内部部分”进行抽象,你就可以实现你的目标:

from abc import ABCMeta, abstractmethod

class Example(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        self.num = 0

    @foo
    def example(self, output):
        return self._example_impl(output)

    @abstractmethod
    def _example_impl(self, output):
        pass

class ExampleSum(Example):
    def _example_impl(self, output):
        self.num = self.num + output

关于python - 如何在基类的函数上使用装饰器,并在继承基类时让装饰器作用于该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800831/

相关文章:

javascript 创建类事件

c++ - 如何将一个数组重新分配给另一个数组?

c++ - 我应该如何在不使用 C++ 中的构造函数的情况下将值(而不是指针)转换为子类?

c++ - 合法使用 initializer_list 来初始化具有派生类型的对象吗?

c++ - 是否可以继承接口(interface)的实现

python - 在前一个文件之上读取文件

python - 有没有办法允许 Django 休息框架的空白数据

python - 需要 SqlAlchemy 单表继承的经典映射器示例

python - 如何将对象存储在动态生成的变量中?

python - Javascript 的 `Date.prototype.toISOString` 的 Python 等价物是什么?