【Python装饰者】在函数测试的作用
#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



StoppableThread类中的
callrun()
判断是否需要stop,需要时就停止循环。
callrun会调用带有阻塞的打印函数print_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装饰者】在函数测试的作用的更多相关文章
- 使用python装饰器计算函数运行时间的实例
使用python装饰器计算函数运行时间的实例 装饰器在python里面有很重要的作用, 如果能够熟练使用,将会大大的提高工作效率 今天就来见识一下 python 装饰器,到底是怎么工作的. 本文主要是 ...
- 关于Python装饰器内层函数为什么要return目标函数的一些个人见解
https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目 ...
- python装饰器中functools.wraps的作用详解
直接上代码看效果: # 定义一个最简单的装饰器 def user_login_data(f): def wrapper(*args, **kwargs): return f(*args, **kwar ...
- Python 装饰器 property() 函数
描述:property() 函数的作用是在新式类中返回属性值. @property 装饰器简单理解就是负责把一个方法变成属性调用 下面理解property()方法语法: class property( ...
- Python装饰器(函数)
闭包 1.作用域L_E_G_B(局部.内嵌.全局...): x=10#全局 def f(): a=5 #嵌套作用域 def inner(): count = 7 #局部变量 print a retur ...
- python装饰器中@wraps作用--修复被装饰后的函数名等属性的改变
Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的functools包中提供了一个叫wraps的de ...
- 万恶之源 - Python装饰器及内置函数
装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...
- Python装饰器及内置函数
装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...
- Python 带参数的装饰器 [2] 函数参数类型检查
在Python中,不知道函数参数类型是一个很正常的事情,特别是在一个大项目里.我见过有些项目里,每一个函数体的前十几行都在检查参数类型,这实在是太麻烦了.而且一旦参数有改动,这部分也需要改动.下面我们 ...
随机推荐
- eclipse中的classes文件夹同步问题
问题: 在同步项目时,由于误操作将classes文件夹加入到了同步版本中,这样会导致每次更新程序编译后,会有很多class文件显示在同步清单中. 解决方案: 将classes文件不设置为同步. 1. ...
- C++ 简单字符串加解密(转载)
#include <iostream.h> #include <windows.h> #include <tchar.h> void EncodeString(LP ...
- DEV MessageBox
DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除所有错误映射数据吗?", "提示&q ...
- Handler sendMessage 与 obtainMessage (sendToTarget)比较
转自:http://iaiai.iteye.com/blog/1992196 obtainmessage()是从消息池中拿来一个msg 不需要另开辟空间new new需要重新申请,效率低,obtian ...
- HDU4329
#include<cstdio> #include<algorithm> #include<map> using namespace std; int main() ...
- json和jsonp
JSON是一种数据交换格式! JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议! 一般使用JSON来传数据,靠JSONP来跨域. JSON的优点: 1.基于纯文本, ...
- document封装一些常用的方法
/** * 批量修改元素样式 */ function css(domObj,styleArry){ for(var i=0;i<styleArry.length;i++){ domObj.sty ...
- SPOJ FTOUR2 - Free tour II
Description 有些黑点,问你选择不超过 \(k\) 个黑点的路径,路径权值最大是多少. Sol 点分治. 这是qzc的论文题,不过我感觉他的翻译好强啊...我还是选择了自己去看题目... 点 ...
- python3 黑板客爬虫闯关游戏(四)
这关较第三关难度增加许多,主要多了并发编程 密码一共有100位,分布在13页,每页打开的时间在15秒左右,所以理所当然的想到要用并发,但是后来发现同IP访问间隔时间不能小于8秒,不然会返回404,所以 ...
- Bootstrap表单验证插件bootstrapValidator使用方法整理
插件介绍 先上一个图: 下载地址:https://github.com/nghuuphuoc/bootstrapvalidator 使用方法:http://www.cnblogs.com/huangc ...