python 装饰器的使用示例
无参修饰,无参数时不需要调用
deflog1(func): func() @log1 deftest(): print('test:')
有参修饰
deflog2(func): definner(*args,**kwargs): func(*args,**kwargs) returninner @log2 deftest(num): print('testlog2:',num,test.__name__) test(20)#相当于log(test(20))
@wraps可以保证装饰器修饰的函数的name的值保持不变
不带参数的装饰器
deflog3(func): @wraps(func) definner(*args,**kwargs,): func(*args,**kwargs) returninner @log3 deftest(num): print('testlog3:',num,test.__name__) test(30)#相当于log(test(30))
带参数的装饰器
deflog4(level): deflog(func): @wraps(func) definner(*args,**kwargs,): iflevel=="warn": print("%sisrunning"%func.__name__) func(*args,**kwargs) returninner returnlog @log4(level="warn") deftest(num): print('testlog4:',num,test.__name__) test(40)
实现带参数和不带参数的装饰器自适应
deflog(arg): ifcallable(arg):#判断参入的参数是否是函数,不带参数的装饰器调用这个分支 deflog3(func): @wraps(func) definner(*args,**kwargs,): func(*args,**kwargs) returninner returnlog3 else: deflog4(func): @wraps(func) definner(*args,**kwargs,): ifarg=="warn": print("%sisrunning"%func.__name__) func(*args,**kwargs) returninner returnlog4 @log(arg=None) deftest(num): print('testlog:',num,test.__name__) test(0)
返回入参出参
deflog5(func): definner(*args,**kwargs): print('入参:',func.__name__,args,kwargs) res=func(*args,**kwargs) print('出参:',func.__name__,res) returnres returninner @log5 deftest(num): print('testlog5:',num,test.__name__) returnnum print(test(50))
类装饰器
classLoging: def__init__(self,level): self.level=level def__call__(self,func): @wraps(func) definner(*args,**kwargs): ifself.level=="warn": self.notify(func) func(*args,**kwargs) returninner defnotify(self,func): print("%sisrunning"%func.__name__) @Loging(level="warn") deftest(num): print('testLoging:',num,test.__name__) test(0)
以上就是python装饰器的使用示例的详细内容,更多关于python装饰器的资料请关注毛票票其它相关文章!