简体   繁体   中英

Can I use the same decorator on a class method and on a static method?

I have a decorator that I use on some class methods. It looks like this

def api_caller(logger_name):
    def api_caller_decorator(method):
        @wraps(method)
        def caller_wrapper(self, *args, **kwargs):
            logger = log_wrap(logger_name)
            kwargs['api'] = create_api_instance(kwargs['api'])
            logger.info('worker authenticated')
            return method(self, logger=logger, *args, **kwargs)
        return caller_wrapper
    return api_caller_decorator

I want to use that decorator outside of the class, is there a way to do it without redefining and manually excluding the self argument?

Since you are not using self , you can include it in the optional args:

    @wraps(method)
    def caller_wrapper(*args, **kwargs):
        ...
        return method(logger=logger, *args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM