问题是您将request_cacher
装饰器定义为带有参数的装饰器,但您忘记传递参数!
考虑这段代码:
import functools
def my_decorator_with_argument(useless_and_wrong):
def wrapper(func):
@functools.wraps(func)
def wrapped(self):
print('wrapped!')
return wrapped
return wrapper
class MyClass(object):
@my_decorator_with_argument
def method(self):
print('method')
@my_decorator_with_argument(None)
def method2(self):
print('method2')
当您尝试method
在一个实例中使用时,您会得到:
>>> inst = MyClass()
>>> inst.method # should be the wrapped function, not wrapper!
<bound method MyClass.wrapper of <bad_decorator.MyClass object at 0x7fed32dc6f50>>
>>> inst.method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bad_decorator.py", line 6, in wrapper
@functools.wraps(func)
File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'MyClass' object has no attribute '__name__'
正确使用装饰器:
>>> inst.method2()
wrapped!
替代修复是从装饰器中删除一层:
def my_simpler_decorator(func):
@functools.wraps(func)
def wrapped(self):
print('wrapped!')
return wrapped
class MyClass(object):
@my_simpler_decorator
def method3(self):
print('method3')
您可以看到它不会引发错误:
>>> inst = MyClass()
>>> inst.method3()
wrapped!