問題是,您將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!
你一定要明白,你所申請的'@ asynchronous'和'@ coroutine'裝飾兩次? – holdenweb
是的,我做。這個可調用的緩存也必須異步工作 – tunaktunak
請發佈完整的追溯,而不僅僅是異常。 –