python decorator
来源:互联网 发布:logo自制软件中文版 编辑:程序博客网 时间:2024/05/29 21:16
无参和有参的装饰器
1:无参装饰器
@decodef foo(): pass
这个类似于:
foo = deco(foo)
2:有参装饰器
有参装饰器需要自己返回以函数作为参数的装饰器
@deco(deco_args)def foo(): pass
这个类似于:
foo = deco(deco_args)(foo)
其中deco(deco_args)需要返回一个函数对象,并且这个函数对象可以接受另一个函数对象作为参数
多个装饰器修饰同一个函数
@deco1(deco_args)@deco2def fun(): pass
这等价于:
fun = deco1(deco_args) (deco2(func)) #其中,deco(deco_args)返回一个函数对象
什么是装饰器?
装饰器实际上就是函数,这些函数接受函数对象。装饰器通常在函数定义的某处嵌入了对目标函数的调用或者至少一次的引用。从本质上看,这类似于java的AOP。
我们可以在装饰器中引入通用功能的代码来降低程序的复杂度,例如,装饰器可以用来:
1:引入日至
2:增加计时逻辑来检测性能
3:给函数加入事物能力
装饰器的例子:
例子1:
from time import ctime, sleepdef recordtime(func): def inner(): print '[%s] %s() called' %(ctime(), func.__name__) func() print '[%s] %s() stoped' %(ctime(), func.__name__) return inner @recordtimedef foo(): sleep(5) foo()
[Thu Dec 17 05:16:27 2015] foo() called[Thu Dec 17 05:16:32 2015] foo() stoped
这个装饰器就是添加了一个计时审计功能
例子2:
from time import timedef logged(when): def log(f, *args, **kargs): print '''Called: function: %s args: %r kargs: %r''' %(f.__name__, 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', name hello('world')
执行结果如下:
hello worldCalled: function: hello args: ('world',) kargs: {}time delta: 0.00204801559448
这里就是一个简单日志记录装饰器
0 0
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- Python decorator
- python decorator
- python decorator
- Python Decorator
- Python Decorator
- python decorator
- Python Decorator
- python decorator
- Python - decorator
- Python Decorator
- Python - Decorator
- python decorator
- Python decorator
- Windows下Qt Creator使用版本控制器Git来进行版本控制,GitHub进行代码托管
- hadoop再次集群搭建(2)-配置免秘钥ssh登录
- ubuntu android环境搭建-转载自google官方网站
- java学习笔记-理解java语言的跨平台
- pat advanced 1107
- python decorator
- WebX实践指南_WebX RPC(四)
- 使用SharedPreferences存储数据
- shell 命令之 find命令二
- Java编写Struts2案例--【用户登录】
- 聚类算法(二):DBSCAN算法
- Xcode乱套了怎么恢复默认设置?
- thinkphp3.2 验证码生成和点击刷新验证码示例
- 依赖倒置、控制反转和依赖注入辨析