試試看:
from functools import wraps
def another_lower_level_decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
return wrapped
def some_abstract_decorator(func):
@wraps(func)
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
@some_abstract_decorator
def test():
""" This is a docstring that should be on the decorated function """
pass
help(test)
打印:
Help on function test in module __main__:
test(*args, **kwargs)
This is a docstring that should be on the decorated function
正如你可以看到它的工作原理!文檔字符串在那裏,分配的名稱。
但這部作品一樣的:
def some_abstract_decorator(func):
@another_lower_level_decorator
@wraps(func)
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
wraps
只是修復了文檔字符串/名稱。只要所有裝飾使用wraps
,其中應用它的順序無所謂
順便說一句,有a much cooler decorator library:
from decorator import decorator
@decorator
def another_decorator(func, *args, **kwargs):
return func(*args, **kwargs)
@decorator
@another_decorator
def some_abstract_decorator(func, *args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
@some_abstract_decorator
def test(x):
""" this is a docstring that should be on the decorated function """
pass
感謝。我認爲你的第一種方式是正確的方式,通過閱讀後。我意識到,如果在應用內部裝飾器後使用'@wrap(func)',我假定內部裝飾器也使用'wrapps(func)'。通過將它應用到裝飾的'wrapper'函數中,我簡單地將'wraps'功能應用到我的結果函數中,從而使事情更加明確(低級裝飾器可能來自第三方等)。 – orokusaki 2010-10-06 18:26:47