I have a problem with a Python decorator.
class decorator(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
print('sth to log: %s : %s' % (self.function.__name__, args))
return self.function(*args, **kwargs)
@decorator
def sum_test(a, b):
print('sum: %s' % (a+b))
@decorator
class Class_test(object):
def __init__(self):
pass
def sum_func(self, a, b):
print('class sum: %s' % (a+b))
return a+b
if __name__ == '__main__':
sum_test(3, 4)
func = Class_test()
var1 = func.sum_func(1, 4)
print(var1)
Output:
sth to log: sum_test : (3, 4)
sum: 7
sth to log: Class_test : ()
class sum: 5
5
The decorator is working as I want for function sum_test
. I can log that function sum_test
was used with variables 3
and 4
.
I have a problem with decorating classes. I can log that object of class Class_test
was created, but I don't have information that function sum_func
was used.
Why is __call__()
in decorator was not triggered when running sum_func
on class object and it was triggered when used directly on function sum_test
?