First, the basic
When we learn about adorners, we first need to review the basics
1The function itself differs from the function call (foo is different from foo ())deffoo ():Print("Hello World")>>> s = foo#Assign the function itself to S>>> type (s)#We're going to look at type S, which is a function type<class 'function'> >>> s ()#And S is the same as Foo itself, with the function of executing functionsHello World>>> s2 = foo ()#The foo function execution result is assigned to S2, where the Foo function has been executedHello World>>>Print(S2)#and we look at our definition of the function, and there is no return value, so S2 nothing (none)None
2. When there are multiple functions with the same name, Python is the def foo () defined before the overwrite definition:print("Hello ")def foo (): print(" World ")>>> foo () World
Second, the decoration device
First we know what the decorator is.
The main function of the adorner is to give the module that has been written, function to add some functions, but do not change the original module code
#Decorative DevicedefOuter (func):defInner (*args, * *Kwargs):Print('Log') ret= Func (*args, * *Kwargs)Print('End') returnretreturnInner@outerdefF1 (ARG,ARG3):Print(ARG,ARG3)return 'xx'>>> F1 (2,3) Log2 3End'xx'#Adorner Use#@ + function name#Features:#1. Automatically executes the outer function and passes the name of its functions F1 when its arguments are passed#2. Re-assign the return value of the outer function to F1
#According to the above example, the @ character omits a series of actions, we take the @ symbol out, the code is like this#pseudo DecoratordefOuter (func):defInner (*args, * *Kwargs):Print('Log') ret= Func (*args, * *Kwargs)Print('End') returnretreturnInnerdefF1 (ARG,ARG3):Print(ARG,ARG3)return 'xx'F1= Outer (F1)#①F1 (2,3)#②
# Output:
Log
2 3
End
' XX '
# pay special attention to me here the function has no parentheses (is not called) # actually, two important parts . # ①. The function is passed into the outer function as a parameter and the outer return value is re-assigned to F1# -and the outer return value is nested inner (note that there is no parentheses in the code), F1 = inner# ②. Re-executing the F1 function that has been "decorated"
# The adorner's @ character only does the ① operation, and we really do "decorate" the operation or do a cleverly nested function (outer),
# Its main function is the above highlights, combined with the decorator and my "pseudo-decorator" code, many times the contrast is easy to see understand
Python Decorator (i)