【发布时间】:2019-10-02 06:23:25
【问题描述】:
我想创建一个装饰器,它是一个类成员,它将装饰一个被装饰的继承方法。
示例代码:
class A(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
@classmethod
def the_decorator(cls, decorated): # <-----this is what i want, with or without self/cls as an argument
def decorator()
#do stuff before
decorated()
print "decorator was called!"
#do stuff after
return decorator
@abstractmethod
def inherited():
raise NotImplemented
class B(A):
def __init__(self):
super(B,self).__init__()
#@A.the_decorator <--- this is what I want,
@overrides
#@A.the_decorator <--- or this
def inherited():
print "B.inherited was invoked"
和
b = B()
b.inherited()
应该输出
B.inherited 被调用
装饰器被调用了!
阅读了this guide on decorators as class members,我仍然无法弄清楚如何使用超类中定义的装饰器来装饰继承的方法。
注意,这里 @overrides 是由 overrides package pip install overrides 定义的
另请注意,我目前使用的是 python 2.7,但我会喜欢 2.7 和 3+ 的答案。
谢谢!
【问题讨论】:
标签: python inheritance decorator