python wraps的作用

时间:2022-07-23
本文章向大家介绍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

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__还是原来的,即函数名称和属性没有变换。