functools.wrap的使用

一、介绍

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 是一个在编写装饰器时非常有用的工具,它可以确保被装饰函数的重要元数据不会丢失。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值