How do I give a decorator acces to the class of a decorated function
Serhiy Storchaka
storchaka at gmail.com
Thu Sep 5 14:32:08 EDT 2019
04.09.19 17:21, Antoon Pardon пише:
> What I am trying to do is the following.
>
> class MyClass (...) :
> @register
> def MyFunction(...)
> ...
>
> What I would want is for the register decorator to somehow create/mutate
> class variable(s) of MyClass.
>
> Is that possible or do I have to rethink my approach?
>
You can make register() returning a descriptor with the __set_name__()
method. A bit of black magic:
class register:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return self.func.__get__(instance, owner)
def __set_name__(self, owner, name):
if not hasattr(owner, 'my_cool_functions'):
owner.my_cool_functions = []
owner.my_cool_functions.append(name)
setattr(owner, name, self.func)
More information about the Python-list
mailing list