Python decorators use the sample

 


Decorator: nature decorator is a function used to decorate other functions, without modifying the source code and is called by its decorative function in case new additional features.

 

Simple no-argument decorator sample:

# Define decorator 
DEF Logger (FUNC):
     DEF wrapper (* args, ** kwargs):
         Print ( " Start ..... " )
         return FUNC (* args, ** kwargs)
         Print ( " End .... " )
    return wapper 

# decorator 
@Logger
 DEF runl ():
     Print ( " runl " ) 

@Logger 
DEF RUN2 (Arg)
    Print ( " RUN2:% S " % Arg)
   return "finished"

if __name__ == "__main__":
    run1()
    run2("hello")

 

Decorator sample to be parameters:

# Define authenticator decorator 
DEF the auth (AUTH_TYPE):
     # parameterized decorative layer requires a multi-parameter receiving function.    
    DEF outer_wrapper (FUNC):
         DEF wrapper (* args, ** kwargs): 
                auth_result = False
                 IF AUTH_TYPE == " basic " :
                     # call basic authentication 
                    auth_result = Basic_Auth () 
    
                 elif AUTH_TYPE == " ldap " :
                     # call ldap Kam right 
                    auth_result = ladp_auth ()
                  the else:
                     # Illegal type 
                IF  Not auth_result:
                     return { " MSG " : " the auth failed " , " Result " : " failed " }
                 the else :
                     return FUNC (* args, ** kwargs) 

# decorator 
@auth (= AUTH_TYPE " LDAP " )
 DEF access_web ()
      # service code 

@auth (AUTH_TYPE = " Basic ")
 DEF access_data ()
      # service code

 

Guess you like

Origin www.cnblogs.com/heyong45/p/11361082.html