我一直在尝试创建一个可以与 python 中的函数和方法一起使用的装饰器。这本身并不难,但是当创建一个接受参数的装饰器时,它似乎是。
class methods(object):
def __init__(self, *_methods):
self.methods = _methods
def __call__(self, func):
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)
上面的代码正确地包装了函数/方法,但在方法的情况下,request
参数是它正在操作的实例,而不是第一个非 self 参数。
有没有办法判断装饰器是否应用于函数而不是方法,并进行相应处理?