python装饰器如何保留原函数信息
发布时间:2024-07-21 20:37:57

说明
1、使用装饰器时,原函数似乎没有变化,但其元信息发生了变化——此时原函数实际上是包裹后的wrapper函数。
2、如果要保留原始函数的元信息,可以内置@functools.wraps(func)实现。
@functools.wraps(func)目标函数的元信息通过update_wrapper和partial复制到wrapper函数中。
实例
#defdecorator
defdecorator_with_args(*args,**kwargs):
print('Step1:enterwrapperwithargsfunc.')
print(args)
print(kwargs)
defdecorator_func(func):
@functools.wraps(func)
defwrapper(*args,**kwargs):
print('Step2:enterwrapperfunc.')
returnfunc(*args,**kwargs)
returnwrapper
returndecorator_func以上是Python装饰器保留原函数信息的方法,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
下一篇 python中树有哪些种类
