当前位置: 首页 > 后端技术 > Python

【Python进阶】装饰器

时间:2023-03-26 13:31:31 Python

什么是装饰器装饰器就是把一个函数作为参数传递给另一个函数(也可以是可调用的可迭代对象),然后再回调。@是四种常见的语法糖形态装饰器1.无参装饰器deflogger(func):defwrapper(*args,**kwargs):print(f'preparetorun{func.__name__}')func(*args,**kwargs)print('finished...')returnwrapper@loggerdefadd(x,y):print(f'{x}+{y}={x+y}')add(1,2)#结果:#准备运行add#1+2=3#finished...2。带参数的装饰器deflogger(level='INFO'):defwrapper(func):defhandle(*args,**kwargs):print(f'{level}:preparetorun{func.__name__}')func(*args,**kwargs)print('finished...')返回句柄returnwrapper@logger('ERROR')defadd(x,y):print(f'{x}+{y}={x+y}')add(1,2)#Result:#ERROR:preparetorunadd#1+2=3#finished...3.当无参类装饰器没有参数时,初始化的参数就是被装饰的函数,即两层结构。classlogger(object):def__init__(self,func):self.func=funcdef__call__(self,*args,**kwargs):print(f'preparetorun{self.func.__name__}')返回自我.func(*args,**kwargs)@loggerdefadd(x,y):print(f'{x}+{y}={x+y}')add(1,2)#Result:#准备runadd#1+2=34带参数的类装饰器有参数时,初始化的参数为装饰函数的参数,即三层结构。类记录器(对象):def__init__(self,level=“INFO”):self。level=leveldef__call__(self,func):defwrapper(*args,**kwargs):print(f'{self.level}:准备运行{func.__name__}')returnfunc(*args,**kwargs)returnwrapper@logger('ERROR')defadd(x,y):print(f'{x}+{y}={x+y}')add(1,2)#结果:#错误:准备运行add#1+2=3使用装饰器的注意事项1.在functools中使用wraps来保留被装饰函数的签名,否则Signedasadecoratorobjectfromfunctoolsimportwrapsdefwrapper(func):@wraps(func)defhandle():passreturnhandle@wrapperdefwrapped():passprint(wrapped.__name__)#结果:#wrapped2.装饰顺序执行顺序:wrapper1>wrapper2(wrapper1装饰wrapper2,wrapper2装饰func)@wrapper1@wrapper2deffunc():pass3.closuredefcounter(func):defwrapper(*args,**kwargs):wrapper.count=wrapper.count+1res=func(*args,**kwargs)print("{0}已被使用:{1}x".format(func.__name__,wrapper.count))returnreswrapper.count=0returnwrapper@counterdefsystem_out(string):print(string)system_out("A")system_out("B")#结果:#A#system_out已使用:1x#B#system_out已使用:2x装饰器实现日志打印、权限控制、处理函数超时的常见场景及代码(待更新)参考https://stackoverflow.com/que...https://zhuanlan.zhihu.com/p/...https://zhuanlan.zhihu.com/p/...