您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页正文

python装饰器如何保留原函数信息

2024-07-17 来源:伴沃教育

说明

1、使用装饰器时,原函数似乎没有改变,但其元信息发生了变化——此时的原函数实际上是包裹后的wrapper函数。

2、若要保留原始函数的元信息,可以通过内置@functools.wraps(func)实现。

@functools.wraps(func)的作用是通过update_wrapper和partial将目标函数的元信息复制到wrapper函数中。

实例

# def decorator
def decorator_with_args(*args, **kwargs):
    print('Step1: enter wrapper with args func.')
    print(args)
    print(kwargs)
 
    def decorator_func(func):
     @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print('Step2: enter wrapper func.')
            return func(*args, **kwargs)
        return wrapper
    return decorator_func

以上就是python装饰器保留原函数信息的方法,希望对大家有所帮助。更多Python学习指路:

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务