1. The first is a very boring function that implements the two number of addition operations:
def f (x, y ): print x+YF (2,3)
Output also OK
5
2. But at this point we feel that the output is too singular, to make the output of the code look less monotonous:
def Showinfo (fun): def Wrap (x, y ): Print " The function before " func (x, y)print"Thefunctionafter" return wrapdef f (x, y ):print x+= Showinfo (f ) F (2,3)
The output at this time:
The function before5 Thefunction after
3. At this point we define a F1 () function that also expects it to have the same output format as the F () function, as long as the Showinfo () function is called before F1 () is executed:
def Showinfo (fun): def wrap (x, y): print " the function before " func (x, y) print " the function after " return wrap def F1 (x, y): print x*yf1 = Showinfo (F1) F1 ( 2, 3)
The function before6 Thefunction after
4. At this point I know you should probably solve the function modification, but you will find that our original meaning is to invoke the F () function, but in the process of invoking the call to use two times to get the effect we want. So we use the adorner method provided by Python to modify our code:
defShowinfo (func):defWrap (x, y):Print "The function before"func (x, y)Print "The function after" returnWrap @showInfodeff (x, y):Printx+y @showInfodefF1 (x, y):Printx*y F (2,3) F1 (2, 3)
This time the results are as follows: We just need to call our function directly to get the result we want.
The function before5 thefunction Afterthe function before6 Thefunction after
Summary: This is where the Python adorner's meaning lies. The callable object in Python includes a function method that implements the class of the __call__ method. Functions in Python are also objects, which can be returned as parameters of higher-order functions or return values. So we can encapsulate a function with a higher-order function, which is the adorner in Python. His grammatical structure is similar to this:
@decorator def func (func):
Pass
Python Learning notes-decorators