What is an adorner?
The adorner itself is a function and adds additional functionality to other functions
The principle of adorners: 1. Do not modify the source code of the Decorated object 2. do not modify the calling method of the decorated object
Adorner = higher order function + function nesting + closure
# Res=timmer (Test) #返回的是wrapper的地址 # res () #执行的是wrapper ()
# Test=timmer (test) #返回的是wrapper的地址 # test () #执行的是wrapper ()
# @timmer is equivalent to Test=timmer (test)
# #搭一个高阶函数与函数嵌套的框架 # def Timmer (func): # def wrapper (): # Print (func) # func () # return Wrapperimport Timedef Timmer (func): def wrapper (): start_time=time.time () # Print (func) Res=func () #由于执行新获得的test , so execute wrapper,func as a local variable, not currently, then go to the previous layer to find, that is, test, run test stop_time = Time.time () print (' Run time is%s '% (Stop_time- start_time)) #wrapper里没有返回值, so no matter how the test is changed, the return value is None return res# since Func runs the test, the value of Func is assigned to Res, Return res is the return value of test wrapper@timmer# equivalent to test = Timmer (test) #把test函数作为参数传给timmer, execution Timmer gets the return value wrapper, and assign it to testdef test (): time.sleep (3) print (' Test run complete ') return ' This is the return value of test ' test () #执行新的test, The actual execution is wrapper, which is to not change the way test is called
Python advanced "Nineth" decorator