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