Suppose we have a class which acts as a decorator
class Foo:
def __init__(self, func):
self.func = func
self.variable1 = 1
self.variable2 = 2
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
It cannot be readily used on an instance method
class Bar:
@Foo
def dance(self):
return 0
Bar().dance() # TypeError: missing 1 required positional argument: 'self'
Is it possible to make dance() behave just like a built-in boundmethod, but also allow it to have additional variables like Bar().dance.variable1?
A related question: we know the undecorated Bar().__dance__ has attribute __self__ pointing to the Bar object. Is it possible to make use of __self__ in variable1?
Fooneeds to be a descriptor, with a__get__method similar to that defined byfunction. Adapted from https://docs.python.org/3/howto/descriptor.html#functions-and-methods:The
__self__attribute you mentioned is an attribute of theMethodTypevalue returned by__get__, not ofdance. (This is becauseBar().dancedoes not evaluate to the functiondance, but to the return value of the__get__method.)It's probably simpler to just not use a class as a decorator, and use a function (which is already a descriptor) instead.