先說總結,白話來講,@wraps相當於是裝飾器的裝飾器。
python內置的方法使用解釋,看起很復雜的樣子┓( ´∀` )┏
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
下面舉個栗子:
from functools import wraps
# 用戶角色權限確認
def permission_required():
def decorator(f):
#@wraps(f)
def decorated_function():
return 'this is decorated function'
return decorated_function
return decorator
# 管理員權限確認
def admin_required(f):
return permission_required()(f)
if __name__=='__main__':
def test_func():
return 'this is test function'
print(admin_required(test_func))
不用@wraps時,打印出來是醬嬸兒的
<function permission_required.<locals>.decorator.<locals>.decorated_function at 0x00000000030411E0>
使用之后看起來清爽了很多
<function test_func at 0x0000000002FC11E0>
通過對比結果,@wraps的作用猜出來個大概。
使用之后它返回的是參數test_func方法的地址。也就是說,如果你想使用參數方法的一些屬性,就需要使用@wraps了。
