You could write an equivalent class-based decorator like this...
(您可以像这样编写等效的基于类的装饰器...)
class addx:
def __new__(self, obj):
obj.x = 10
return obj
@addx
class A:
pass
assert A.x == 10
...but I don't think this really gets you anything.
(...但是我认为这真的不能给您带来任何好处。)
The utility of a class-based decorator becomes more apparent when your goal is to modify objects of class A
, rather than class A
itself. (当您的目标是修改class A
对象而不是class A
本身的对象时,基于类的装饰器的实用程序将变得更加明显。)
Compare the following two decorators, one function based and one class based: (比较以下两个修饰符,一个基于函数,一个基于类:)
def addx_func(kls):
def wrapper():
res = kls()
res.x = 10
return res
return wrapper
class addx_class:
def __init__(self, kls):
self.kls = kls
def __call__(self):
res = self.kls()
res.x = 10
return res
@addx_func
class A:
pass
@addx_class
class B:
pass
a = A()
assert a.x == 10
b = B()
assert b.x == 10
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…