Using the same decorator (with arguments) with functions and methods

后端 未结 5 1524
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 00:54

I have been trying to create a decorator that can be used with both functions and methods in python. This on it\'s own is not that hard, but when creating a decorator that

5条回答
  •  死守一世寂寞
    2020-12-05 01:44

    Since you're already defining a __get__ to use your decorator on the Bound Method, you could pass a flag telling it if it's being used on a method or function.

    class methods(object):
        def __init__(self, *_methods, called_on_method=False):
            self.methods = _methods
            self.called_on_method
    
        def __call__(self, func):
            if self.called_on_method:
                def inner(self, request, *args, **kwargs):
                    print request
                    return func(request, *args, **kwargs)
            else:
                def inner(request, *args, **kwargs):
                    print request
                    return func(request, *args, **kwargs)
            return inner
    
        def __get__(self, obj, type=None):
            if obj is None:
                return self
            new_func = self.func.__get__(obj, type)
            return self.__class__(new_func, called_on_method=True)
    

提交回复
热议问题