The reason the adorner appears is because we are dealing with new requirements: In the case of not changing the way the original function is called, the extension function is added before and after the function, and its essence is the closure function.
The structure of the adorner:
def Timmer (func): def Inner (*args,**Kwargs): " Add extension code before function call " = Func (*args,**kwargs) ' Add extension code after function call ' ' return ret return inner
Two def two return correspond to one another.
The design pattern of the adorner is the open closure principle, which is open to the extension and closed to the modification.
Calculate the run time of a function:
Import TimedefTimmer (func):#function names can be used as arguments to functions definner (): Start=time.time () func () End=time.time ()Print(End-start)returnInnerdefhahaha (): Time.sleep (0.1) Print('AAAA')#hahaha ()Timmer (hahaha) ()
This function can calculate the limited code run time, facing the enterprise large-scale application This method is not feasible. You need to use the following method:
Import TimedefTimmer (func):#function names can be used as arguments to functions definner (): Start=time.time () func () End=time.time ()Print(End-start)returnInnerdefhahaha (): Time.sleep (0.1) Print('AAAA')#hahaha ()#Timmer (hahaha) ()#We can't change the way this function is called.#You can't modify the original code .hahaha = Timmer (hahaha)#the address of the Timmer function is given to hahahaHahaha ()#Actually, the Timmer is executed.
This is the simple application of adorners.
We need to streamline this by:
Import TimedefTimmer (func):#function names can be used as arguments to functions definner (): Start=time.time () func () End=time.time ()Print(End-start)returnInner@timmer#The syntax sugar must follow the defined functiondefhahaha (): Time.sleep (0.1) Print('AAAA')#hahaha ()#Timmer (hahaha) ()#We can't change the way this function is called.#You can't modify the original code .#hahaha = Timmer (hahaha) #timmer函数的地址给了hahahaHahaha ()#Actually, the Timmer is executed.
If the decorated function has parameters to pass in it:
def Timmer (func): # ---> hahaha def Inner (*args,**kwargs): # can accept any arguments passed in # Span style= "COLOR: #008000" >args = = Kwargs = = {} # *args = = **kwargs = = a =1,b = 2 func (*args,**kwargs) #--->hahaha return inner def KKK (a): Span style= "COLOR: #0000ff" >print (a) KKK = Timmer (KKK) KKK ( 1)
The decorated function has a return value, which can be resolved in the following way:
def Timmer (func): #---> jjj def inner (*args,**Kwargs): = func (*args,**kwargs) # --->ret = jjj () return ret return innerdef jjj (): return 123= Timmer (JJJ) Print (JJJ ()) # ==>inner
Python Learning decorator