Note the python decorator

Python parameters in function may be a function, when a plurality of functions required to achieve the same code can also be considered to process the decorator.

Assume the following scenario, we need to query and view the profile operation, then before this general need to log into the system, then you can login function written decorator function

. 1  DEF Login (Fun): # decorator function format, the function defines a function in the inner layer, the inner layer while the function returns the function itself, a function corresponding to the implementation of the inner MSG 
2      DEF MSG ():
 . 3          Print ( ' successful login ' )
 . 4          Fun ()
 . 5      return MSG
 . 6  
. 7 @login     # decorator Login 
. 8  DEF search1 ():   # Once decorative function is performed automatically decorator function login, and corresponds to the function parameter decorators 
. 9      Print ( ' query succeeds ' )
 10  
. 11  @login
 12 is  DEF Profile ():
 13 is      Print (' You are welcome to view the profile ' )

The above code, is decorative login function, search1, profile interpretation meaning of this code is a function of decorator detail:
1, automatic login function and perform a function as a parameter to be decorated login function to process
2, the login the return value msg re-assign the function to be decorated
3, once bound to the decorator, calls are executed msg the functions essentially to be decorated () function
4, after the function to be decorated, the decoration function re-assigned to the decorator the inner function

The following parameters have to look at the situation decorative function

. 1  DEF loginxt (Fun):
 2      DEF MSG (* args, ** kwargs):
 . 3          R & lt Fun = (* args, ** kwargs)
 . 4          IF R & lt:
 . 5              return R & lt
 . 6      return MSG
 . 7  
. 8  @loginxt
 . 9  DEF Order (name , pwd):
 10      IF name == ' ADMIN '  and pwd == ' 123456 ' :
 11          return ( ' welcome you log ' )
 12      the else :
 13         return ( ' log in ' )
 14  
15  
16  Print (Order ( ' ADMIN ' , ' 123456 ' ))

Guess you like

Origin www.cnblogs.com/heertong/p/12128236.html