【Python】 Python中的functools.wraps:装饰器的优雅包装

基本原理

在Python中,装饰器是一种非常强大的工具,它允许我们以一种非常灵活的方式修改或增强函数的行为。装饰器本质上是一个函数,它接收一个函数作为参数,并返回一个新的函数。然而,当我们使用装饰器时,原始函数的一些属性,如其名字和文档字符串,可能会丢失。为了解决这个问题,functools模块提供了一个名为wraps的装饰器工厂,它可以“包装”原始函数的属性,确保它们在装饰后仍然保持不变。

代码示例

示例1:没有使用wraps的装饰器
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# 输出:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
print(say_hello.__name__)  # 输出:wrapper
示例2:使用wraps的装饰器
from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    """Greets everyone."""
    print("Hello!")

say_hello()
# 输出:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
print(say_hello.__name__)  # 输出:say_hello
print(say_hello.__doc__)   # 输出:Greets everyone.
示例3:wraps的更多属性
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("Arguments:", args)
        print("Keyword arguments:", kwargs)
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def add(a, b):
    """Adds two numbers."""
    return a + b

result = add(5, 3)
print(result)  # 输出:Arguments: (5, 3) Keyword arguments: {}

注意事项

  1. 使用场景:当你需要编写一个装饰器,并且希望保留原始函数的名称、文档字符串等属性时,应该使用wraps
  2. 参数传递wraps可以正确处理函数的参数,包括可变参数和关键字参数。
  3. 兼容性wrapsfunctools模块的一部分,因此它在Python 2和Python 3中都可用,但使用方式略有不同。在Python 3中,wraps可以直接用作装饰器;而在Python 2中,你需要先将其作为参数传递给update_wrapper函数。
  4. 性能考虑:虽然wraps提供了方便的功能,但它可能会略微影响性能,因为它需要在内部进行一些属性的复制工作。

结论

functools.wraps是一个非常重要的工具,它使得装饰器的使用更加灵活和强大。通过保留原始函数的元数据,wraps帮助我们编写更加清晰、可维护的代码。理解并正确使用wraps,可以让你的Python代码更加专业和优雅。

>
> 【痕迹】QQ+微信朋友圈和聊天记录分析工具1.0.4 (1)纯Python语言实现,使用Flask后端,本地分析,不上传个人数据。
>
> (2)内含QQ、微信聊天记录保存到本地的方法,真正实现自己数据自己管理。
>
> (3)数据可视化分析QQ、微信聊天记录,提取某一天的聊天记录与大模型对话。
>
> 下载地址:https://www.alipan.com/s/x6fqXe1jVg1
>

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值