gpt4 book ai didi

python - 如何在类中声明装饰器来装饰已经装饰的继承方法?

转载 作者:行者123 更新时间:2023-12-01 00:57:19 27 4
gpt4 key购买 nike

我想创建一个装饰器,它是一个类成员,它将装饰一个继承的方法,该方法被装饰。

示例代码:

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 was invoked

decorator was called!

<小时/>

已阅读 this guide on decorators as class members ,我仍然无法弄清楚如何使用父类(super class)中定义的装饰器来装饰继承的方法。

<小时/>

注意,这里@overrides是由overridespackage定义的。 pip install 覆盖

<小时/>

另请注意,我目前使用的是 python 2.7,但会喜欢 2.7 和 3+ 答案。

谢谢!

最佳答案

你还没有那么远!

关键是装饰器将接收一个参数,该参数是装饰函数,因此它只能是一种统计方法。而且您还忘记了应该使用 self 参数声明普通方法。

但是这段代码应该可以工作:

class A(object):
__metaclass__ = ABCMeta
def __init__(self):
pass

@staticmethod
def the_decorator(decorated): # <-----this is what i want, with or without self/cls as an argument
def decorator(self):
#do stuff before
decorated(self)
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(self):
print "B.inherited was invoked"

我可以在 Python 2.7 下测试它,除了 @overrides 装饰器(我在测试中评论了它)

关于python - 如何在类中声明装饰器来装饰已经装饰的继承方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com