python wraps的作用

前端之家收集整理的这篇文章主要介绍了python wraps的作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

def my_decorator(func):
    def wrapper(*args,**kwargs):
        '''decorator'''
        print('Decorated function...')
        return func(*args,1)">kwargs)
    return wrapper
@my_decorator
test(): """Testword""" 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
 my_decorator(func):
    @wraps(func)
     wrapper
@my_decorator
)
输出:
Decorated function...
Test function
test Testword

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

 

猜你在找的Python相关文章