I want functions in a class to store their returned values in some data structure. For this purpose I want to use a decorator:
results = []
instances = []
class A:
def __init__(self, data):
self.data = data
@decorator
def f1(self, a, b):
return self.data + a + b
@decorator
def f2(self, a):
return self.data + a + 1
x = A(1)
x.f1(1, 2)
x.f2(3)
print(results)
The question is, how to implement this decorator.
The main idea is the following:
class Wrapper:
def __init__(self, func):
self.func = func
def __call__(self, *args):
res = self.func(*args)
results.append(res)
instances.append(args[0])
def decorator(func):
return Wrapper(func)
But then I am getting an error message:
TypeError: f1() missing 1 required positional argument: 'b'
This question is similar to what other people asked (How to decorate a method inside a class?, Python functools.wraps equivalent for classes), but it is not clear where to put @functools.wraps
or to call @functools.update_wrapped()
in my case.