当前位置: 首页 > Python编程 > Python编程实战技能 > Python编程基础入门 > Python内置的wraps装饰器有什么用

Python内置的wraps装饰器有什么用

发布时间:2020年09月27日 10:28:01 来源: 点击量:475

【摘要】Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的f

Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最好在实现之前加上functools的wrap,它能保留原有函数的名称和docstring。

wraps内置方法的作用

查看一个函数的帮助文档有两种方法:

func_name.__doc__
help(func_name)

先来看一个例子,定义timmer装饰器和index函数,并且都添加了帮助文档。

import time
def timmer(func):
    def inner(*args,**kwargs):
        'wrapper inner function'
        start_time=time.time()
        res=func(*args,**kwargs)
        end_time=time.time()
        print("run time: %s " %(end_time-start_time))
        return res
    return inner
def index():
    'index function'
    time.sleep(2)
    print("welcome to index page")

在index没有被timmer装饰前,来查看index的帮助文档:

print(index.__doc__)

程序运行结果:

index function

然后为index添加timmer装饰器,再次查看index函数的帮助文档:

import time
def timmer(func):
    def inner(*args,**kwargs):
        'wrapper inner function'
        start_time=time.time()
        res=func(*args,**kwargs)
        end_time=time.time()
        print("run time: %s " %(end_time-start_time))
        return res
    return inner
@timmer
def index():
    'index function'
    time.sleep(2)
    print("welcome to index page")
print(index.__doc__)

程序运行结果:

wrapper inner function

可以看到,在为index函数添加装饰器后,index函数的帮助文档变成装饰器timmer内部函数的帮助文档了。

换句话说,就是原始index函数内部的数据被装饰器timmer修改了。

相关推荐:《Python视频教程》

怎么样才能在保留原始被装饰函数的数据的前提下,为函数添加新功能呢??就是python内置的wraps装饰器。

导入wraps装饰器,修改上面的代码,为timmer的内部函数添加wraps装饰器,然后再次查看被装饰函数的帮助文档:

import time
from functools import wraps
def timmer(func):
    @wraps(func)
    def inner(*args,**kwargs):
        'wrapper inner function'
        start_time=time.time()
        res=func(*args,**kwargs)
        end_time=time.time()
        print("run time: %s " %(end_time-start_time))
        return res
    return inner
@timmer
def index():
    'index function'
    time.sleep(2)
    print("welcome to index page")
print(index.__doc__)

运行程序,执行结果如下:

index function

可以看到,index函数即使添加了装饰器,其内部的原始数据仍然没有被装饰器修改。

从上面的示例可以看出,wraps装饰器的作用就是保留被装饰对象的原始数据信息。

实例一:

不加wraps

# -*- coding=utf-8 -*- 
from functools import wraps   
def my_decorator(func):
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Calling decorated function...')
        return func(*args, **kwargs)
    return wrapper  
 
@my_decorator 
def example():
    """Docstring""" 
    print('Called example function')
print(example.__name__, example.__doc__)

执行结果:

('wrapper', 'decorator')

实例二:

加wraps

# -*- coding=utf-8 -*- 
from functools import wraps   
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Calling decorated function...')
        return func(*args, **kwargs)
    return wrapper  
 
@my_decorator 
def example():
    """Docstring""" 
    print('Called example function')
print(example.__name__, example.__doc__)

执行结果:

('example', 'Docstring')

总结:

warps 作用: 消除(被装饰后的函数名等属性的改变)副作用。

相关推荐:

Python之被装饰函数参数的设置与定义

分享到: 编辑:wangmin

就业培训申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

绑定手机号

应《中华人民共和国网络安全法》加强实名认证机制要求,同时为更加全面的体验产品服务,烦请您绑定手机号.

预约成功

本直播为付费学员的直播课节

请您购买课程后再预约

环球青藤移动课堂APP 直播、听课。职达未来!

安卓版

下载

iPhone版

下载
环球青藤官方微信服务平台

刷题看课 APP下载

免费直播 一键购课

代报名等人工服务

课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部