python functools.wraps保留被装饰函数属性

作用

普通装饰器 ,会覆盖函数名称,并且 会替换 函数 文档字符串

介绍

functools.wraps(wrapped[, assigned][, updated])
This is a convenience function for invoking partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) as a function decorator when defining a wrapper function. For example:

from functools import wraps
def my_decorator(f):
… @wraps(f)
… def wrapper(*args, **kwds):
… print ‘Calling decorated function’
… return f(*args, **kwds)
… return wrapper

@my_decorator
… def example():
… “”“Docstring”“”
… print ‘Called example function’

example()
Calling decorated function
Called example function
example.name
‘example’
example.doc
‘Docstring’
Without the use of this decorator factory, the name of the example function would have been ‘wrapper’, and the docstring of the original example() would have been lost.

你可能感兴趣的:(python,装饰器)