您的位置:首页 > 编程语言 > Python开发

[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)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: