【说站】python装饰器如何保留原函数信息
2024-12-13
41
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装饰器保留原函数信息的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
更新于:1个月前赞一波!3
相关文章
- 【说站】Python kmeans聚类的使用
- 【说站】Python中concurrent.futures模块如何使用
- 【说站】javascript如何声明函数
- 【说站】Python curses库如何使用
- 【说站】Python字典常用方法汇总
- 【说站】Python字符串方法如何使用
- 【说站】javascript递归函数如何使用
- 【说站】javascript回调函数的异步探究
- 【说站】Python列表操作方法的整理
- 【说站】Python中os模块的功能介绍
- 【说站】python模块的搜索顺序分析
- 【说站】python抛出raise异常的注意点
- 【说站】Python psd-tools如何转换文件
- 【说站】python异常的传递
- 网站统计中的访问信息收集的前端实现
- 【说站】python自定义日志如何实现
- 【说站】python有哪些注释的种类
- 【说站】js中diff函数的使用
- 【说站】js中isBefore函数如何判断
- 【说站】python中__new__的重写
文章评论
评论问答