zoukankan      html  css  js  c++  java
  • 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+'
    ')
    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+'
    ')
        f.close()
    
    write_log('log.txt', '记录2')
  • 相关阅读:
    【读书笔记】之《把时间当做朋友》
    软件工程——五大模型
    VB中的GetUserName函数
    VB中 vbp vbw frm frx log bas 等扩展名大全
    【机房收费系统】——基本数据设定的理解
    在64位WindowsServer2012R2中安装Oracle10g第二版(10.2.0.4.0)-20160106
    Linux——vi命令详解
    使用Postman测试WebService接口
    npm和yarn的淘宝镜像添加
    yarn配置私有registry
  • 原文地址:https://www.cnblogs.com/linximf/p/11407085.html
Copyright © 2011-2022 走看看