使用functools.wraps完善装饰器

在python中使用装饰器(decorator)会使得被装饰函数的名称和帮助文档发生错乱,如下所示:

>>> def decorator(f):
...     def wrapper(*args, **kwargs):
...         """wrapper Docstring"""
...         print('Calling decorated function')
...         return f(*args, **kwargs)
...     return wrapper
... 
>>> @decorator
... def example():
...     """example Docstring"""
...     print('Called example function')
... 
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'wrapper'
>>> example.__doc__
'wrapper Docstring'

从上例中可以看出,在使用装饰器后,函数example的name和doc都变成了wrapper的name和doc,名称和帮助文档发生了错乱。

在decorator中使用functools中的wraps可以很好的解决这个问题,上例改为:

>>> from functools import wraps
>>> def decorator(f):
...     @wraps(f)
...     def wrapper(*args, **kwargs):
...         """wrapper Docstring"""
...         print('Calling decorated function')
...         return f(*args, **kwargs)
...     return wrapper
... 
>>> @decorator
... def example():
...     """example Docstring"""
...     print('Called example function')
... 
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'example Docstring'

使用wraps之后,被装饰函数example的名称和帮助文档得以正确体现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值