一、介绍
functools.wraps 是 Python 标准库中的一个函数,用于帮助创建装饰器时保留被装饰函数的元数据(如函数名、文档字符串等)。在使用装饰器时,如果不使用 functools.wraps,则被装饰函数的一些元数据可能会丢失或被覆盖。
二、不使用functools.wraps
from functools import wraps
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs) # 调用原始函数
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
"""This is the docstring of say_hello function."""
print("Hello!")
print(say_hello.__name__) # 输出函数名,而不是"wrapper"
print(say_hello.__doc__) # 输出函数文档字符串,而不是None

三、使用functools.wraps
from functools import wraps
def my_decorator(func):
@wraps(func) # 使用wraps装饰器
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs) # 调用原始函数
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
"""This is the docstring of say_hello function."""
print("Hello!")
print(say_hello.__name__) # 输出函数名,而不是"wrapper"
print(say_hello.__doc__) # 输出函数文档字符串,而不是None

在这个示例中,使用 @wraps(func) 装饰器将被装饰函数的元数据复制到了 wrapper 函数中,使得 say_hello 保留了其原始的函数名和文档字符串。
总之,functools.wraps 是一个在编写装饰器时非常有用的工具,它可以确保被装饰函数的重要元数据不会丢失。








![[管理与领导-27]:IT基层管理者 - 团队管理 - 育人 - 如何评估团队的能力?如何培养团队?](https://img-blog.csdnimg.cn/img_convert/807bcf4d77434fb6d9c925f4c2f0fdf7.jpeg)










