How can I define decorator method inside class? [duplicate]

While I don’t think this is completely needed all the time, here is how you would make a decorator within your class. It is a little more cumbersome because of the way the methods become bound to the self later on. Normally with plain function decorators you don’t have to worry about that.

The requirements are:

  1. The decorator needs to be defined first before the methods that will use it
  2. It needs to use functools.wraps to preserve the bound methods properly

Example:

from functools import wraps

class myclass:
    def __init__(self):
        self.start = False

    def _with_check(f):
        @wraps(f)
        def wrapped(inst, *args, **kwargs):
            if inst.check():
                return
            return f(inst, *args, **kwargs)
        return wrapped

    def check(self):
        return self.start

    @_with_check
    def doA(self):
        print('A')

    @_with_check
    def doB(self):
        print('B')

I made it a protected member since it is not really something someone else needs to use outside of the class. And it still preserves your public check() call for use by itself. The decorator simply wraps calling it first before calling the target method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)