
说明
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基础教程