【发布时间】:2020-11-08 03:20:04
【问题描述】:
我正在实现What is the Python equivalent of static variables inside a function? 中描述的装饰器。在答案中,装饰器具有正常功能,并且在我的环境中也可以使用。
现在我想把装饰器放到一个类方法上。
源代码:
#decorator
def static_variabls(**kwargs):
def new_func(old_func):
for key in kwargs:
setattr(old_func, key, kwargs[key])
return old_func
return new_func
class C:
@static_variabls(counter = 1)
def f_(self) -> None:
print(self.f_.counter)
self.f_.counter += 1
c1 = C()
c1.f_()
c1.f_()
c1.f_()
预期结果:
1
2
3
实际结果:
1
Traceback (most recent call last):
File "1.py", line 16, in <module>
c1.f_()
File "1.py", line 13, in f_
self.f_.counter += 1
AttributeError: 'method' object has no attribute 'counter'
我不明白为什么这段代码不起作用。根据错误消息,self.f_.counter 不存在但print(self.f_.counter) 有效。这里发生了什么?
【问题讨论】: