Abstract: A company's basic development platform, there are probably more than n functions, the boss requires small a, for each function to add the authorization function, and requires not modify the function internal structure, let small a try to start from outside the code, as a novice small A, this is undoubtedly a huge workload, Do you want a TM to add to the inside not ~ ~ ~ ~ Born No love small a helpless looking at the desktop, in the sweep of Google browser icon that moment, suddenly a tight, so witty open Google search, to find a simple method, After searching in a LOWB blog called the Silver Corner King found a thing called the adorner, and then patiently looked down ...
Diagram of the Python decorator execution flow
1 #Use of adorners2 #automatically executes the outer function and passes the function name F1 below as a parameter3 #re-assign the return value of the outer function to F14 #1, Encounter def outer (func) loaded into memory, skip function body5 #2, encountered @outer, the F1 as a parameter passed into the Func6 #3. Encounter def inner (): Load function into memory skip function body7 #4, encountered return inner, the inner function as a whole, assign value to F18 #5, Encounter F1 (), call inner function body, execute print (' log ')9 #6. The Function body print (' F1 ') that encounters return func () executing the old F1 function as a parameter passed into FuncTen #7, encountered return ' Lululu ' will lululu back to F1 () One defOuter (func): A definner (): - Print('Log') - returnfunc () the returnInner - @outer - defF1 (): - Print('F1') + return 'Lululu' - Print(F1 ()) +>>>Log A>>>F1 at>>>lululu
#Pass with ParametersdefOuter (func):defInner (a):Print('before') R=func (a)Print(' After') returnRreturnInner@outerdefF1 (ARG):Print(ARG)return 'Lululu'Print(F1 ('Huhuh'))>>>before>>>Huhuh>>> After>>>Lululu#Universal Parameter TransferdefOuter (func):defInner (*args,**Kwargs):Print('before') R=func (*args,**Kwargs)Print(' After') returnRreturnInner@outerdefF1 (ARG):Print('F1 function Body', Arg)return 'Lululu'Print('return value', F1 ('Huhuhu'))>>>before>>>F1 function Body Huhuhu>>> After>>>return value Lululu@outerdefF2 (A1,A2):Print('F2 function Body','F2') return 'AA' 'BB'Print('return value', F2 ('Hu','Lu'))>>>before>>>F2 function Body F2>>> After>>> return value AABB
Use of python-day4-decorators