试试看:
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