ITPub博客

首页 > IT职业 > IT图书 > python装饰器如何保留原函数信息

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

IT图书 作者:anleli 时间:2021-09-11 09:53:18 0 删除 编辑

说明

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学习指路:python基础教程

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2548/viewspace-2829623/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    93
  • 访问量
    1071