python之“装饰器”

在python里装饰器

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

装饰器有两个特点:

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

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

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

装饰器用到的知识:

  1、函数可以作为变量传递给另一个函数

  2、函数的返回值也可以是另一个函数

装饰器实现代码:

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

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')

猜你喜欢

转载自www.cnblogs.com/linximf/p/11407085.html