一个简单的场景:我有一个装饰器,用来给函数计时,现在我想给函数的运行时间加上一个时间偏移time_lag,这个时间偏移不是一个常量,我想通过参数传入装饰器实现。实现一:importtimefromfunctoolsimportwrapsdeftimer_func(func,time_lag):@wraps(func)defwer(*args,**kwargs):t1=time.time()r=func(*args,**kwargs)t2=time.time()cost=t2-t1+time_lagprint('timecost%s'%cost)returnrreturnwerdeffunc(n:int):whilen>0:n=n-1返回na=timer_func(func,time_lag=10)a(1000000)但是这种实现方式不能语法糖@,每次都必须通过函数调用来实现,失去了装饰器简洁方便的特点。因此,使用另一种实现方式,只需要在原来的装饰函数外再嵌套一层外层函数,将要传入装饰器的函数传入最外层函数即可。实现方法如下:实现方法二:fromfunctoolsimportwrapsimporttimedeftimer(time_lag):defdecorator(func):@wraps(func)defwer(*args,**kwargs):t1=time.time()r=func(*args,**kwargs)t2=time.time()cost=t2-t1res=cost+time_lagprint('timecost%s'%res)returnfunc(*args,**kwargs)#返回函数本身的结果returnwer#returninnerfunctionreturndecorator#Returnouterfunctiondeffunc(n:int):'''thisisafunctest:paramn:::return:'''whilen>0:n=n-1returnn>>>a=timer(10)#返回外部函数,#passintime_lag=10>>>print(a)
