【引言】
我们经常需要多函数进行耗时测试,测试方法有许多,这里介绍装饰者的方法,提高耗时测试代码的可复用性,在其他方面的应用也是如此。
【设计原则】
类应该对扩展开放,对修改关闭。
【代码】
(1)定义装饰者具体方法
#encoding: UTF-8
'''
Created on 2016��12��7��
@filename: test.py
@author: YYH
'''
import time
from functools import wraps class TimeRecorder:
def __init__(self, name="function"):
  print(name +"()"+ " Start...")
  print(name +"()"+ " Running...")
  self.name = name
  self.startTime = time.time()
def __del__(self):
  print("{0}() Ended,Cost Time:{1} s".format(self.name, time.time() - self.startTime))
#使用装饰者测试函数运行时间,这里看起来像是“钩子”的方法,实际并不是的,借助于Python的装饰者,这个方法将发挥巨大的作用。
def fn_timer(function):
  @wraps(function) #解决打印函数名的bug
  def function_timer(*args, **kwargs):
    tR=TimeRecorder(function.__name__) #增加变量,由使得该对象的生命器存在整个函数
    result = function(*args, **kwargs)
    return result
  return function_timer
(2)定义装饰者(该方法就就具有fn_timer的“能力”)
(3)使用装饰者
(4)结果
 
【实例二】增加指示函数正在执行的打印语句
  一开始,我的 想法是通过对线程的销毁来实现这个功能,但是python提供的线程并不提供stop方法,需要自己实现,由自己来管理。(想想python这样做也是有道理的,毕竟,如果线程有一些资源没有释放就贝强制退出了,是十分危险的事情)
  所有我使用最简单的方法,继承Threading.Thread; 然后在需要定时调用的函数

    
StoppableThread类中的
callrun()
判断是否需要stop,需要时就停止循环。
callrun会调用带有阻塞的打印函数print_running
  然后使用装饰者模式,为某个function 添加定时打印running的功能。
  具体实现可以参考代码
#encoding: UTF-8
'''
Created on 2016��12��7��
@filename: test.py
@author: YYH
@version: 1.1: 增加了打印函数参数(args 和 kwargs)
'''
import time
from functools import wraps
from Crypto.SelfTest.Signature.test_pkcs1_15 import isStr
from numba.types import none class TimeRecorder:
def __init__(self,argstr=''): print(argstr+ " Start...")
print(argstr+ " Running...")
self.argstr = argstr
self.startTime = time.time()
def __del__(self):
print("{0} Ended,Cost Time:{1} s".format(self.argstr, time.time() - self.startTime))
#使用装饰者测试函数运行时间
def fn_timer(function):
@wraps(function) #解决打印函数名的bug
def function_timer(*args, **kwargs):
argStr = str(locals())#得到参数字符串
tR=TimeRecorder(argstr=argStr) #增加变量,由使得该对象的生命器存在整个函数
result = function(*args, **kwargs)
return result
return function_timer
#定时执行的函数
import threading
# http://stackoverflow.com/questions/18018033/how-to-stop-a-looping-thread-in-python
#创建允许销毁的线程类 使用继承
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition.""" def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None):
threading.Thread.__init__(self, group, self.callrun, name, args, kwargs, verbose)
self.setDaemon(True)
self.callback = target
self._stop = threading.Event() def stop(self):
self._stop.set()
def stopped(self):
return self._stopEvt.isSet() def callrun(self,*args,**kwargs):
while self._stop.isSet() == False:
self.callback(*args,**kwargs)
#使用装饰者添加定时打印信息
def print_running(funcname="function"):
time.sleep(1)
print("<"+funcname+" running..."+">")
def run_indicate(function):
@wraps(function) #解决打印函数名的bug
def function_timer(*args, **kwargs):
st=StoppableThread(target=print_running,kwargs={'funcname':function.__name__}) #增加变量,由使得该对象的生命器存在整个函数
argDict = locals()#function得到参数字符串
argStr = ""
argStr = argStr+str(argDict['function'])+'; '
argStr = argStr+'args:'+str(argDict['args'])+'; '
argStr = argStr+'kwargs:'+str(argDict['kwargs'])+'; ' tR=TimeRecorder(argstr=argStr) #增加变量,由使得该对象的生命器存在整个函数
st.start()
result = function(*args, **kwargs)
st.stop()
st.join(1) #等待线程结束
return result
return function_timer

【使用方法】与上面类似

【运行结果示例】

【Python装饰者】在函数测试的作用的更多相关文章

  1. 使用python装饰器计算函数运行时间的实例

    使用python装饰器计算函数运行时间的实例 装饰器在python里面有很重要的作用, 如果能够熟练使用,将会大大的提高工作效率 今天就来见识一下 python 装饰器,到底是怎么工作的. 本文主要是 ...

  2. 关于Python装饰器内层函数为什么要return目标函数的一些个人见解

    https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目 ...

  3. python装饰器中functools.wraps的作用详解

    直接上代码看效果: # 定义一个最简单的装饰器 def user_login_data(f): def wrapper(*args, **kwargs): return f(*args, **kwar ...

  4. Python 装饰器 property() 函数

    描述:property() 函数的作用是在新式类中返回属性值. @property 装饰器简单理解就是负责把一个方法变成属性调用 下面理解property()方法语法: class property( ...

  5. Python装饰器(函数)

    闭包 1.作用域L_E_G_B(局部.内嵌.全局...): x=10#全局 def f(): a=5 #嵌套作用域 def inner(): count = 7 #局部变量 print a retur ...

  6. python装饰器中@wraps作用--修复被装饰后的函数名等属性的改变

    Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的functools包中提供了一个叫wraps的de ...

  7. 万恶之源 - Python装饰器及内置函数

    装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...

  8. Python装饰器及内置函数

    装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...

  9. Python 带参数的装饰器 [2] 函数参数类型检查

    在Python中,不知道函数参数类型是一个很正常的事情,特别是在一个大项目里.我见过有些项目里,每一个函数体的前十几行都在检查参数类型,这实在是太麻烦了.而且一旦参数有改动,这部分也需要改动.下面我们 ...

随机推荐

  1. WCF技术内幕 第二章 - 简单的Message

    1.契约 - 接口 (客户端和服务端都要认识Message) namespace WCFService { [ServiceContract(Namespace = "http://wint ...

  2. Elasticsearch Configuration 中文版

    ##################### Elasticsearch Configuration Example ##################### # This file contains ...

  3. 分布式的Id生成器

    项目中需要一个分布式的Id生成器,twitter的Snowflake中这个既简单又高效,网上找的Java版本 package com.cqfc.id; import org.slf4j.Logger; ...

  4. Error:failed to find Build Tools revision 23.0.0 rc3

    解决,选择AS里有的版本就可以了,已有的我这就一个23.0.3,导入的项目是23.0.2 Donate:)

  5. oracle 视图的创建,游标,left join

    视图的创建: create or replace view dmv_mat_contract_stock_in_bill as select csib.*, sib.STOCK_IO_, sib.CO ...

  6. 项目vue2.0仿外卖APP(三)

    项目的结构如下:                   项目资源准备 准备项目的各种图片资源等等 注意:在webpack可以不用css sprite,直接用单张图片,因为它会帮忙打包. 还有SVG图片, ...

  7. [BZOJ1251]序列终结者

    [BZOJ1251]序列终结者 试题描述 网上有许多题,就是给定一个序列,要你支持几种操作:A.B.C.D.一看另一道题,又是一个序列 要支持几种操作:D.C.B.A.尤其是我们这里的某人,出模拟试题 ...

  8. 基于log4net的帮助类Log

    using log4net; using System; using System.Collections.Generic; using System.Diagnostics; using Syste ...

  9. ./configure,make,make install的作用

    这些都是典型的使用GNU的AUTOCONF和AUTOMAKE产生的程序的安装步骤. ./configure是用来检测你的安装平台的目标特征的.比如它会检测你是不是有CC或GCC,并不是需要CC或GCC ...

  10. root切换

    1.su -i root.password 2.su passwd root pass pass su pass 3.su -val 一般用户名 4.