【Python】 Python装饰器的魔法:深入理解functools.wraps

基本原理

在Python中,装饰器是一种设计模式,用于修改或增强函数或方法的功能。functools.wraps是一个装饰器工厂,它用来帮助我们保持被装饰函数的元数据,比如函数的名字、文档字符串等。

当你创建一个装饰器时,你可能会无意中覆盖掉原始函数的一些属性。例如,如果你直接返回一个新函数,那么原始函数的名字和文档字符串等信息就会丢失。functools.wraps的作用就是用来解决这个问题,它能够让装饰后的函数保持原始函数的这些元数据。

代码示例

示例1:没有使用functools.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():
    """This function says hello"""
    print("Hello!")

say_hello()
print(say_hello.__name__)
print(say_hello.__doc__)

运行结果:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.
wrapper
None
示例2:使用functools.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():
    """This function says hello"""
    print("Hello!")

say_hello()
print(say_hello.__name__)
print(say_hello.__doc__)

运行结果:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.
say_hello
This function says hello
示例3:使用functools.wraps并传递参数
from functools import wraps

def my_decorator(text):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"{text} before calling {func.__name__}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@my_decorator("Something is happening")
def greet(name):
    """Greet someone"""
    print(f"Hello, {name}!")

greet("Alice")
print(greet.__name__)
print(greet.__doc__)

运行结果:

Something is happening before calling greet
Hello, Alice!
greet
Greet someone

注意事项

  • 使用functools.wraps时,它应该作为内部装饰器,即@wraps(func)的形式,而不是@wraps
  • functools.wraps可以传递给装饰器工厂函数,这样每个生成的装饰器都会保持原始函数的元数据。
  • 如果你的装饰器需要修改函数的行为,并且你想要保留原始函数的元数据,那么使用functools.wraps是一个很好的实践。

结论

functools.wraps是一个强大的工具,它帮助我们在不破坏原有函数元数据的前提下,增强函数的功能。通过使用functools.wraps,我们可以编写更加清晰、可维护的代码,同时保留函数的名称、文档字符串等重要信息。这对于代码的可读性和调试都非常有帮助。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值