Both versions of python decorators

Previous article introduces the concept of the decorator. Now talk about how to write the decorator in the program. On the code:

 1 def X(fun):
 2     def Y(b):
 3         print(b)
 4         fun()
 5     return Y
 6 
 7 def test():
 8      print('OK')
 9 
10 test = X(test)
11 test(1)

The first five lines is a closure, as a function of parameters of the inner layer is a variable function of the outer layer function returns a reference to memory functions.

Line 10, when calling the function X, the function of the reference test (test note not (), no parentheses) as a parameter, X-case (test) returns a reference to the function Y. So the result is the tenth row of test points to Y function references. So, test line 11 () is a reference to the function called Y, while Y function in fun () points to the test line 7 () function.

The second writing:

 1 def X(fun):
 2     def Y(b):
 3         print(b)
 4         fun()
 5     return Y
 6 
 7 @X    #相当于 test = X(test)
 8 def test():
 9      print('OK')
10 
11 test(1)

@ In python is called syntactic sugar, with the @X test = X (test) is equivalent to, the above two methods are equivalent, but the first method shows a more intuitive decorators, and the second comparator wording beautiful and simple.

Guess you like

Origin www.cnblogs.com/GouQ/p/11728469.html