How do I give a decorator acces to the class of a decorated function

dieter dieter at handshake.de
Thu Sep 5 00:44:55 EDT 2019


Antoon Pardon <antoon.pardon at vub.be> writes:
> 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?

As others have already explained: the decoration works an the
function (not the method) level. A function knows nothing of a class.

Others have already pointed out work arounds.
I add an additional one:
Instead of:
  class C:
    ...
    @decorate
    def f(...): ...
    ...
you can use:
  class C:
    ...
    def f(...): ...
    ...
  decorate(C, C.f)

In Python 2, "C.f" returns a method (an object with a
reference to the class and the function) - there, you would
not need the class parameter for "decorate".
In Python 3, however, "C.f" is the function (without any reference
to the class.




More information about the Python-list mailing list