[Python]学习装饰器语法
2016-01-29 01:14
796 查看
阅读材料
https://www.python.org/dev/peps/pep-0318/http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000
装饰器语法
The current syntax for function decorators as implemented in Python 2.4a2 is:@dec2 @dec1 def func(arg1, arg2, ...): pass
This is equivalent to:
def func(arg1, arg2, ...): pass func = dec2(dec1(func))
装饰器会接收func作为参数,添加一些功能,然后返回一个函数
这种行为看起来就像是复合函数,例如 z(x) = g(f(x))
在装饰器声明的时候也可以传入参数
如果说最基本的装饰器是“二次函数”的话(因为它返回一个函数),那么这种返回装饰器的行为就像是“三次函数”
The current syntax also allows decorator declarations to call a function that returns a decorator:
@decomaker(argA, argB, …)
def func(arg1, arg2, …):
pass
This is equivalent to:
func = decomaker(argA, argB, …)(func)
Examples
可以参阅PEP 0318 的 example 小节这里给一个简单的例子
decorators.py
from time import time # 函数运行完后,打印运行时间 def mytime(func): def wrapper(*args, **kwargs): start = time() ret = func(*args, **kwargs) print 'run seconds: %.3f' % (time() - start) return ret return wrapper # @mytime def foo(): sq = [i**2 for i in range(100000)]
相关文章推荐
- python文件操作--字符串替换
- Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
- Python环境搭建之OpenCV的步骤方法
- Python读写ini配置文件
- Python学习第六天
- python学习笔记-Day13 -css基础知识
- Python 常见异常列表
- Mac上Python从2.x升级到3.x的艰苦历程
- python的学习,28,1,2016
- python学习笔记-Day13-- 前端知识 html
- Pyhton 8.2 多线程
- 【Python】给pypy安装第三方库
- Python--多线程
- python中的一些小知识(一)
- python-装饰器
- python和R混合编程
- python-函数式编程
- python学习之7 JSON编码
- Python 爬虫备份人人状态(及评论)
- 多进程,多线程,协程