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')
  • 相关阅读:
    Go语言入门系列(三)之数组和切片
    详解Java的对象创建
    Go语言入门系列(二)之基础语法总结
    Go语言入门系列(一)之Go的安装和使用
    SpringCloud--Ribbon--配置详解
    自己动手作图深入理解二叉树、满二叉树及完全二叉树
    自已动手作图搞清楚AVL树
    《RabbitMQ》什么是死信队列
    《RabbitMQ》如何保证消息不被重复消费
    《RabbitMQ》如何保证消息的可靠性
  • 原文地址:https://www.cnblogs.com/linximf/p/11407085.html
Copyright © 2011-2022 走看看