好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

查看更多关于python装饰器如何保留原函数信息的详细内容...

  阅读:22次