The python decorator learning

# Speaking before the first talk decorator nested function 
# defined: in vivo function of another function redeclaration 
X = 0
 DEF Test (): 
    X =. 1
     Print ( " in The Test " )
     DEF TEST_1 (): 
       X = 2
        Print ( " in The TEST_1 " )
        DEF   test_2 (): 
           X =. 3
            Print ( ' in The test_2 ' )
            Print (. 3 ) 
       test_2 () 
    TEST_1 () 
Test () 
# output:
# in the test
# in the test_1
# in the test_2
# 3
# Essentially a function of the role is to add additional features as a function decorator 
# principle: decorator can not modify the source code is decorative function and can not be invoked to modify the way decorative function 
Import Time
 DEF the Test (): 
    the time.sleep ( 3 )
     Print ( " in at the test " )
 # now I want to add a new feature in the test function is to run the test statistics function much time is spent 
DEF the Timer (FUNC): 
    start_time = time.time () 
    FUNC () 
    stop_time = time.time ( )
     Print ( " total consumption of time; {} " .format (stop_time- start_time)) 
the Timer (the Test) 
# run results: 
# in the Test at The
# Total spending time; 3.0066416263580322 
# While doing so to achieve this functionality, there is no test to modify the source code, but modified the function is called, so be improved by adding the following nested functions
# Realized through nested function 
Import Time
 DEF Test (): 
    the time.sleep ( . 3 )
     Print ( " in The Test " ) 

DEF Timer (FUNC):
     DEF docarote (): 
        START_TIME = the time.time () 
        FUNC () 
        stop_time = the time.time ()
         Print ( " total consumption time; {} " .format (stop_time- START_TIME))
     return docarote 
Test = Timer (Test) 
Test () 
# run results 
#the Test at The in 
# Total spending time; 3.0049240589141846

 While the above step to achieve this for the test () function to add new features, there is no way to change his call, but more test = timer (test), so the final look decorator

# Realized through nested function 
Import Time
 DEF Timer (FUNC):
     DEF docarote (): 
        START_TIME = the time.time () 
        FUNC () 
        stop_time = the time.time ()
         Print ( " total consumption time; {} " .format (stop_time- start_time))
     return docarote 
@timer   # this step is equivalent to the Timer = the Test (the Test) 
DEF the Test (): 
    the time.sleep ( 3 )
     Print ( " in the Test at The " ) 
the Test () 
# operating results 
#the Test at The in 
# Total spending time; 3.0049240589141846

 

Guess you like

Origin www.cnblogs.com/Be-your-own-hero/p/11298753.html