The syntax of sugar does not benefit the computer's operation, but the benefits for programmers are great, so that we can write code, so called sugar
#****************************** Decorator *************************#The adorner is essentially a Python function that allows other functions to add additional functionality without any code changes, and the return value of the adorner is also a function object. #application Scenarios for adorners: such as insert log, performance test, transaction processing, caching, etc.Import Timedeffunc1 ():Print('In func1')defTimer (func):definner (): Start=time.time () func ()#the Func obtained here is the formal parameter, and the parameter is given to the func1, so the func1 () is executed here . Print(Time.time ()-start)returninnerfunc1= Timer (func1)#func1 passed as a parameter to the Timer function, the timer function returns a inner return value assigned to FUNC1,FUNC1 () or inner ()func1 ()#Timer This function is used to calculate the run time of other functions (formal parameters as function names)
#******** decorator syntax sugar ******Import TimedefTimer (func):definner (): Start=time.time () func ()Print(Time.time ()-start)returnInner@timer#==> func1 = Timer (func1) In addition to this statement, the other statements are the same, and @timer is equivalent to the timer (FUNC1) statement, #This @timer statement is equivalent to associating the timer function with the next function adjacent to it in the form func1 = Timer (func1).deffunc1 ():Print('In func1') Time.sleep (1)#delay 1sdefFunc2 ():Print('In Func2') Time.sleep (2)#delay 2sfunc1 () Func2 ( )#In func1#1.0009326934814453 output is more than 1s, it is obvious that the FUNC1 function extends the timing function#In Func2
Import TimedefTimer (func):definner (): Start=time.time () func ()Print(Time.time ()-start)returnInner@timer#==> func1 = Timer (func1) In addition to this statement, the other statements are the same, and @timer is equivalent to the timer (FUNC1) statement, #This @timer statement is equivalent to associating the timer function with the next function adjacent to it in the form func1 = Timer (func1).defFunc2 ():Print('In Func2') Time.sleep (2)#delay 2sdeffunc1 ():Print('In func1') Time.sleep (1)#delay 1sfunc1 () Func2 ( )#In func1#In Func2#2.0009799003601074 #这次因为func2和timer相邻, so fun2 extended the chronograph function
Python Learning day07 Higher order function adorner syntax sugar