我想用一个装饰做一些准备工作,并记录状态的功能也有,所以我写类似的东西:类作为装饰类方法
class Decorator:
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1 # Simply count the call times
return self.func(self, *args, **kwargs)
class Foo:
def __init__(self):
self.value = 0
@Decorator
def test(self, value):
self.value = value # change the value of instance
print(self.value)
f = Foo()
f.test(1)
print(f.value)
print(f.test.value)
但很明显,self
在__call__(self, *args, **kwargs)
对应例如Decorator
而不是Foo
的实例,这将使f.value
不变,但是f.test.value
增加。
有没有什么办法可以将Foo
的实例传递给Decorator
而不是Decorator
本身?
还是有什么办法可以更清楚的实现这个功能吗?
谢谢先进。
什么f.test.value办? –
我200%确定我没有完全理解你的问题。就像在你的代码中一样,你想记录一次调用@Decorator的方法的次数。这很好,但你以后如何访问** count **。我试过一个例子,你可以将** Foo **的实例传递给** Decorator **,但是f.test.value不起作用 –
你可以使用'f.test.count'访问count,其中'f '是'Foo'的一个实例。 – Leon