python中wraps的详解

1.__name__用来显示函数的名称,__doc__用来显示文档字符串也就是(""“文档字符串”"")这里面的内容

2.首先我们来看不加@wraps的例子

def my_decorator(func):
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Decorated function...')
        return func(*args, **kwargs)
    return wrapper
@my_decorator
def test():
    """Testword"""
    print('Test function')
test()
print(test.__name__, test.__doc__)

#输出:
Decorated function...
Test function
wrapper decorator

我们来看执行的整个过程:在调用test()函数时,首先会调用装饰器(将test作为参数传入到装饰器中),执wrapper函数,再执行test函数。

但我们可以看到test函数的名字:__name__为wrapper,__doc__为decorator,已经不是原来的test函数了。

接下来,我们使用@wraps

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from functools import wraps
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Decorated function...')
        return func(*args, **kwargs)
    return wrapper
@my_decorator
def test():
    """Testword"""
    print('Test function')
test()
print(test.__name__, test.__doc__)

#输出:
Decorated function...
Test function
test Testword

我们会发现,test函数的__name____doc__还是原来的,即函数名称和属性没有变换。

结尾给大家推荐一个非常好的学习教程,希望对你学习Python有帮助!

Python基础入门教程推荐:更多Python视频教程-关注B站:Python学习者
https://www.bilibili.com/video/BV1LL4y1h7ny?share_source=copy_web

Python爬虫案例教程推荐:更多Python视频教程-关注B站:Python学习者
https://www.bilibili.com/video/BV1QZ4y1N7YA?share_source=copy_web

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值