How to define a decorator as method inside class in Python?
class myclass: def __init__(self): self.cnt = 0 def counter(self, function): """ this method counts the number of runtime of a function """ def wrapper(**args): function(self, **args) self.cnt += 1 print('Counter inside wrapper: ', self.cnt) return wrapper global counter_object counter_object = myclass() @counter_object.counter def somefunc(self): print("Somefunc called") somefunc() print(counter_object.cnt) somefunc() print(counter_object.cnt) somefunc() print(counter_object.cnt)
Output
Somefunc called Counter inside wrapper: 1 1 Somefunc called Counter inside wrapper: 2 2 Somefunc called Counter inside wrapper: 3 3