###
Now that I have a simple myfunc function, now I want to add functionality to the MyFunc function. Below we add a Deco feature.
Import TimedefDeco (func): StartTime=time.time () func () EndTime=time.time () msecs= (EndTime-startTime)Print("-->elapsed Time%s s"%msecs)defmyfunc ():Print('Start MyFunc') Time.sleep (3) Print('End MyFunc') Deco (MyFunc)
However, there is a problem with this approach, which modifies the original invocation method of MyFunc: MyFunc ()------> becomes deco (myfunc). So we made the following changes.
###
def Deco (func): def wrapper (): = Time.time () func () = time.time () = (EndTime- startTime) Print("-->elapsed time%s s"%msecs) return Wrapper # # #返回的是 <function deco.<locals>.wrapper at 0x03234468> can be called via wrapper ()
Def myfunc ():
Print (' Start myfunc ')
Time.sleep (3)
Print (' End MyFunc ')
Print ("MyFunc is%s"%myfunc.__name__)
Myfunc=deco (MyFunc)
Print ("MyFunc is%s"%myfunc.__name__)
MyFunc ()
Output Result:
MyFunc is MyFunc
MyFunc is wrapper
Start MyFunc
End MyFunc
-->elapsed Time 3.0007433891296387 S
After the above changes, a more complete adorner (DECO) is implemented, the adorner has no effect on the original function, and the code of the function call.
The notable thing in the example is that Python is all objects and functions, so the code changes the function object corresponding to "MyFunc".
###
defDeco (func):defwrapper (): StartTime=time.time () func () EndTime=time.time () msecs= (EndTime-startTime)Print("-->elapsed Time%s s"%msecs)returnWrapper@decodefmyfunc ():Print('Start MyFunc') Time.sleep (3) Print('End MyFunc') MyFunc ()
###
Python # Decorator