python之“装饰器”

在python里装饰器python

其定义:装饰器就是一个函数,用来装饰其余函数,就是给其余函数添加功能。编程

装饰器有两个特色:函数

  一、装饰器不修改被装饰函数的源码;spa

  二、装饰器不锈钢被装饰函数的调用方式。日志

在编程中常常会有一些公共函数,在已经发布的程序中,为了程序的稳定性原函数是不容许随便修改其源代码的,而且合做开发中也不容许修改调用方式,那么若是要对原函数进行功能增长,怎么办呢?这时装饰器解决了这个问题。code

装饰器用到的知识:blog

  一、函数能够做为变量传递给另外一个函数utf-8

  二、函数的返回值也能够是另外一个函数开发

装饰器实现代码:源码

有一个公共函数,做用是写日志文件:

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

若是想对这个写日志文件函数增长一个写文件时间监控,这里增长一个写日志文件函数的装饰器:

import time

def write_log_time(func):
    def n_wite_log(filename,*msg_info):
        s_time=time.time()
        #参数:*msg_info 表明这个参数可传递也可不传递,例如只给文件名的日志,内容为记录时间
        func(filename,*msg_info)
        e_time=time.time()
        print('write log file times:%s' %(e_time-s_time))
    return n_wite_log

使用方法为在函数write_log前加一个@write_log_time

完整代码:

import time

def write_log_time(func):
    def n_wite_log(filename,*msg_info):
        s_time=time.time()
        #参数:*msg_info 表明这个参数可传递也可不传递,例如只给文件名的日志,内容为记录时间
        func(filename,*msg_info)
        e_time=time.time()
        print('write log file 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')
相关文章
相关标签/搜索