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

410次阅读
没有评论

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

说明

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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-06-16发表,共计563字。
新手QQ群:570568346,欢迎进群讨论 Python51学习