I'm implementing the decorator described in What is the Python equivalent of static variables inside a function?. In the answer, the decorator is put on a normal function and it worked also in my environment.
Now I'd like to put the decorator onto a class method.
Source Code:
#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_()
Expected Result:
1
2
3
Actual Result:
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'
I don't understand why this code doesn't work. According to the error message, self.f_.counter
doesn't exist but print(self.f_.counter)
works. What's happening here?