python核心编程学习(七)
来源:互联网 发布:win7照相机软件下载 编辑:程序博客网 时间:2024/05/29 09:15
一个装饰器+闭包的demo,个人感觉很像spring的注解+aop 呵呵:
'''Created on 2012-3-8@author: Administrator'''#!/usr/bin/env pythonfrom time import timedef logged(when): def log(f,*args,**kargs): print '''called:function:%s args:%r kargs:%r''' % (f,args,kargs) def pre_logged(f): def wrapper(*args,**kargs): log(f,*args,**kargs) return f(*args,**kargs) return wrapper def post_logged(f): def wrapper(*args,**kargs): now = time() try: return f(*args,**kargs) finally: log(f,*args,**kargs) print 'time delta:%s' %(time()-now) return wrapper try: return {'pre':pre_logged,'post':post_logged}[when] except KeyError,e: raise ValueError(e),'must be pre or post'@logged('post')def hello(name): print 'Hello,',namehello('world')
运行结果如下:
Hello, worldcalled:function:<function hello at 0x01AC1D30> args:('world',) kargs:{}time delta:0.0
注意要点如下:
1、调用hello('world')时实际上是调用了logged方法包装后的hello方法。
2、在logged方法中会根据@logged('post')中的'post'找到post_logged(f)内部函数。
3、post_logged中的wrapper负责先调用目标函数,然后执行记录日志的操作。
4、模式和java的代理模式很相似。
5、注意*args,**kargs两参数出现的位置和时机。
6、最后一事一直不明,就是f的参数是怎么传递给wrapper的?
- python核心编程学习(七)
- Python核心编程学习笔记(七)
- python核心编程学习笔记-2016-09-14-03-Web编程(七)
- python核心编程学习
- Python--核心编程学习
- python核心编程(七)—字典和集合
- python核心编程学习笔记(一)
- Python核心编程学习笔记(三)
- python核心编程学习(一)
- python核心编程学习(二)
- python核心编程学习(三)
- python核心编程学习(四)
- python核心编程学习(五)
- python核心编程学习(六)
- python核心编程学习笔记(1)
- Python核心编程学习笔记(一)
- Python核心编程学习笔记(二)
- Python核心编程学习笔记(三)
- 使用freeChart 例子
- SDRAM之我见(转)
- 解析Spring IOC原理——工厂模式与反射机制的综合应用
- 来自数据源的string类型的给定值不能转换为指定目标列的类型nvarchar
- NSString+NSMutableString+NSValue+NSAraay用法汇总
- python核心编程学习(七)
- 2008--2009年北京航空航天大学计算机研究生机试真题
- poj3440
- 网站性能并发测试工具
- MVC日积月累 经典学习
- [MSSQL]SQL Server 2008 Using the MERGE statement
- JAVA学习——容器(概述)
- CGGeometry.h
- 正向代理与反向代理