我有一个基类 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
行为在 ExampleSum
的 example
函数中而不显式编码。
最佳答案
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/