The python "decorator"

In python in decorator

Definition: decorator is a function used to decorate other functions that add functionality to other functions.

Decorator has two characteristics:

  1, decorative function does not modify the source code to be decorated;

  2, is called by the decorator stainless steel decorative function.

In programming, there is often some public functions, the program has been released, to the stability of the original function of this program is not allowed to tinker with the source code, and development cooperation can not be modified invocation, so if you want the original function function increase, how to do it? Then decorator solves this problem.

Decorators use of knowledge:

  1, can function as a variable to another function

  2, the return value of the function may be a function of another

Decorator implementation code:

There is a public function, is to write the log file:

1 def write_log(filenmae, msg_info):
2     f = open(filenmae, 'a+', encoding='utf-8');
3     f.write(msg_info+'\n')
4     f.close()

If you want to add this function to write the log file a written document time monitoring, log file write here to add a function decorator:

Import Time 

DEF write_log_time (FUNC):
     DEF n_wite_log (filename, * msg_info): 
        S_TIME = time.time ()
         # parameters: * msg_info represent this parameter can be passed or not passed, for example, only the file name to log the contents of the recording time 
        FUNC (filename, * msg_info) 
        e_time = the time.time ()
         Print ( ' Write File log Times: S% ' % (e_time- S_TIME))
     return n_wite_log

Use as before plus a function write_log @write_log_time

Complete code:

Import Time 

DEF write_log_time (FUNC):
     DEF n_wite_log (filename, * msg_info): 
        S_TIME = time.time ()
         # parameters: * msg_info represent this parameter can be passed or not passed, for example, only the file name to log the contents of the recording time 
        FUNC (filename, * msg_info) 
        e_time = the time.time ()
         Print ( ' Write File log Times: S% ' % (e_time- S_TIME))
     return n_wite_log 

@write_log_time 
DEF write_log (filenmae, msg_info): 
    F = Open (filenmae, ' A + ' , encoding = 'utf-8');
    f.write(msg_info+'\n')
    f.close()

write_log('log.txt', '记录2')

 

Guess you like

Origin www.cnblogs.com/linximf/p/11407085.html