I want a decorator that would add the decorated function to list, like this :
class My_Class(object):
def __init__(self):
self.list=[]
@decorator
def my_function(self)
print 'Hi'
I expect my_function to be added to self.list, but I just can’t write this decorator. If I try to write it inside My_Class, then I would have to use @self.decorator, and self does not exist since we’re outside any function. And if I try to write it out of My_Class, then I can’t retrieve self from my_function.
I know quite similar questions exist, but they are overly complicated, and I’m just learning python and decorators.
You can’t access
selffrom the decorator, because the decorator is run at the time the function is defined, and at that time there are no instances ofMy_Classyet.It’s better to put the function list as a class attribute instead of an instance attribute. Then you can pass this list as a parameter to the decorator:
Now you can access
MyClass.funcListto get the list of decorated functions.