【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中,不知道函数参数类型是一个很正常的事情,特别是在一个大项目里.我见过有些项目里,每一个函数体的前十几行都在检查参数类型,这实在是太麻烦了.而且一旦参数有改动,这部分也需要改动.下面我们 ...
随机推荐
- Mac Pro 日历增强工具 Itsycal
Mac 自带的日历工具一点也不好用,好在 Itsycal 弥补了这个缺陷,效果图如下: 下载地址:https://www.mowglii.com/itsycal/,下载解压后,把 Itsycal.ap ...
- iis虚拟目录实现分布式文件服务器
前提:假定有2台服务器:服务器a和服务器b,则服务器a和b须在同一局域网内 服务器设定:a为web服务器,b为文件服务器.这里服务器环境是:Windows Server 2008 R2 大致步骤如下: ...
- 在centos 7.0上利用yum一键安装mono
首先我们需要先配置一下yum源中mono的引用说明: 第一步: vi /etc/yum.repos.d/mono.repo 第二步:在刚打开的文件中编辑如下内容 [mono]name=monobase ...
- 打不死的redis集群
导读 最近遇到部分系统因为redis服务挂掉,导致部分服务不可用.所以希望搭建一个redis集群镜像,把原先散落各处的redis服务器统一管理起来,并且保障高可用和故障自动迁移. 最近遇到部分系统因为 ...
- 已安装php 编译安装 gd库拓展模块
参考资料:http://wenku.baidu.com/link?url=EgXFShYxeJOZSYNQ_7RCBC-6X8OcRRCqVm4qCv49uBk57d6vLBoUpfYdQ-KqJRs ...
- ABAP 将单元格设置编辑状态 FORM
FORM set_style USING fieldname style TYPE string CHANGING ...
- 在win7环境下批量修改文件权限
在附件->命令提示符->右键->以管理员身份运行 进入你需要修改的文件位置,然后输入下面两条命令 takeown /f * /A /R icacls * /t /grant:r ev ...
- Linux 昨天时间
今天date +%F昨天date -d yesterday +%F明天date -d tomorrow +%F七天前date -d "7 days ago" +%F
- 关于控件的Invoke(...)方法和BeginInvoke(...)方法的区别
这两个方法最主要的区别就是一个是同步,一个是异步,即会阻塞线程,那么阻塞哪个线程呢?我们用代码来分析(工具是VS2010) using System; using System.Collections ...
- 图文相关性 flickr数据实验结论_1
初始化的选取很重要,random_uniform的效果远远好于random_normal, 是否有bias对效果影响很小 红色是random_uniform初始化,对比random_normal初始化 ...