Advanced Python (decorator)

from datetime Import datetime
 DEF log (FUNC): # FUNC expressed as a function of acting on the decorative 
    DEF warpper (* args, ** kW): # warpper decorator returns to action functions and parameters, as well as perform additional functions of encapsulation print ( '% S Call' FUNC .__ name__%) 
        Print ( ' Call S% ' % FUNC. the __name__ ) # print now in the implementation of the function name of the function 
        return FUNC (* args, ** kW)
     return warpper 

DEF that log1 ( text):
     DEF Decorator (FUNC):
         DEF warpper (* args, ** kW):
             Print ( ' % S% S '% (Text, FUNC. The __name__ )) # multi-package decoration layer, a principle above, and can customize the parameters passed string 
            return FUNC (* args, ** kW)
         return warpper
     return Decorator 

DEF the getTime (FUNC) : # attaining the objective function execution time decorator 
    DEF wrapper (* args, ** kw): 
        Start = DateTime.Now () 
        RES = FUNC (* args, ** kw) 
        End = DateTime.Now ()
         Print (End - Start)
         return RES
     return wrapper 

DEF logging (Level): #Log function to set the target level decorator 
    DEF warpper (FUNC):
         DEF innerWrapper (* args, ** kW):
             Print ( ' [{IS} Level Enter function FUNC {} ()] ' .format ( 
                Level = Level, 
                FUNC = FUNC 
            )) 
            return FUNC
         return innerWrapper
     return warpper 

@getTime 
DEF now ():
     Print (123 ) 

@log 
DEF now1 ():
     Print ( ' 2016-01-03 ') 

@ Log1 ( ' custom name dynamic print ' )
 DEF now2 ():
     Print ( ' 2016-01-03 ' ) 

@logging (Level = ' DEBUG ' )
 DEF now3 ():
     Print ( ' 123456789 ' ) 

# now ( ) 123 0:00:00 
# now1 () Call now1 2016-01-03 
# now2 () moving the print customized name 2016-01-03 now2 
# now3 () [Enter the DEBUG IS function <function now3 AT 0x000001D3B4721EA0> () ]    

 

Guess you like

Origin www.cnblogs.com/xingxingclassroom/p/11112229.html