(a) The forming process of the adorner
the essence of the adorner is an application of the closure function , which is used to decorate the function of the original function without modifying the original function and its calling mode.
#simple non-parametric adornerImport TimedefTimmer (func):definner (): Start=time.time () func () End=time.time ()Print(End-start)returnInner @timmer # grammar sugardefhahaha (): Time.sleep (2)#a usage of stop time Print("a") hahaha ()
#simple function decorator with parametric functionsImport TimedefTimmer (func):definner (x, y): Start=time.time () func (x, y) end=time.time ()Print(End-start)returnInner@timmerdefhahaha (A, B): Time.sleep (2)#a usage of stop time Print("AAA") hahaha ()
#simple adorner with return valueImport TimedefTimmer (func):defInner (*args,**Kwargs): Start=time.time () se= Func (*args,**Kwargs) End=time.time ()Print(End-start)returnSEreturnInner@timmerdefFunc2 (a):Print("In func and get a:%s"%(a))return "fun2 over"Func2 ([1,2,3,4,5])
The main function of the adorner and the fixed structure of the adorner
The main functions of the adorner:
The function is added after the function without changing the original function and its calling method.
Fixed format for adorners:
# Perfect Adorner format def Wrapper (func): def Inner (*args,**Kwargs): "' to do before execution ' = Func (*args,**kwargs) " ' return ' after executing function re return Inner
Adorner with parameters
#Adorner Multilayer Nestingdefouter (flag):defTimer (func):defInner (*args,**Kwargs):ifflag:Print("what to do before executing a function") Re= Func (*args,**Kwargs)ifflag:Print("what to do after the function is executed") returnRereturnInnerreturnTimer@outer ("Hello World")#The adorner can also be used to transmit parametersdeffunc (A, b):Print(111) func (1, 3)
Open Closure principle
1, for the extension is open, any one program, it is not possible at the beginning of the design has been able to think of all the features and future do not make any changes. So we have to allow code extensions to add new functionality.
2, the modification is closed, we write a function, it is likely to have been delivered to other people to use, if we modify it at this time, it is likely to affect other users already in use of the function.
The adorner perfectly follows this open and closed principle.
Multiple adorners decorate the same function
defWrapper1 (func):definner ():Print("wrapper1,before func") func ()Print("wrapper1,after func") returnInnerdefWrapper2 (func):definner ():Print("Wrapper2, before Func") func ()Print("wrapper2,before func") returnInner@wrapper1@wrapper2deff ():Print("In F") F ()
Python path-Adorner function