python装饰器@wraps应用
不改变使用装饰器原有函数的结构(如name, doc)
示例:不使用@wraps()
def decorator(func): def wrapper(*args, **kwargs): """this is wrapper __doc__""" print("this is wrapper method") return func(*args, **kwargs) return wrapper @decorator def test(): """this is test __doc__""" print("this is test method") print("__name__: ", test.__name__) print("__doc__: ", test.__doc__) # 结果 # __name__: wrapper # __doc__: this is wrapper __doc__
示例:使用@wraps()
from functools import wraps def decorator(func): @wraps(func) def wrapper(*args, **kwargs): print("this is wrapper method") return func(*args, **kwargs) return wrapper @decorator def test(): print("this is test method") print("__name__: ", test.__name__) print("__doc__: ", test.__doc__) """ 结果: __name__: test __doc__: this is test __doc__ """
在写装饰器时想要不改变函数结构需要添加@wraps()装饰器