Decorators in Python are a very powerful feature that I’m still learning to wrap my head around. While working on one of my projects I wanted to use a decorator to ‘register’ the decorated object, which is pretty easy:
def register(func): pass class Sample: @register def method(self): # register this method pass
This worked great, except I realized I needed to pass the function that was being registered and another parameter that I was able to sometimes figure out automatically. In the cases when I was unable to figure it out, I need to pass the parameter with the decorator, so I changed the decorator to a class:
class register: def __init(self, param=None): self.param = param def __call__(self, func): pass
This worked great — I was able to set param to what I needed, but I had trouble with my old code. It took me a little bit to realize that
__call__ was not being … called. I needed to change the code to use
class Sample: @register() def method(self): # register this method pass
After looking for at several examples, it was sort of “by accident” that I found this. It may well be documented, but I certainly missed it: if you use decorator classes, you need to explicitly call your decorator!