[Python] Can a decorator of an instance method access the class?

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.

    def decorator(view):
    # do something that requires view's class
    print view.im_class
    return view

    class ModelA(object):
    @decorator
    def a_method(self):
    # do some stuff
    pass


    The code as-is gives:


    AttributeError: 'function' object has no attribute 'im_class'
    ​

    I found similar question/answers - Python decorator makes function forget that it belongs to a class and Get class in Python decorator - but these rely upon a workaround that grabs the instance at run-time by snatching the first parameter. In my case, I will be calling the method based upon the information gleaned from its class, so I can't wait for a call to come in.

    Continue reading...

Compartilhe esta Página