概念
装饰器(Decorator)的基本定义:“装饰器的功能是将被装饰的函数当作参数传递给与装饰器对应的函数(名称相同的函数),并返回包装后的被装饰的函数”。
装饰器的定义是:装饰器实质上是一个函数。它把一个函数作为输入并且返回另外一个函数。其实其是闭包概念的深化
优点
抽离出大量函数中与函数功能本身无关的雷同代码并继续重用
可以将函数“修饰”为完全不同的行为,可以有效的将业务逻辑正交分解,如用于将权限和身份验证从业务中独立出来
概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能
装饰器入门
In [43]: def foo():
...: print('in foo()')
...: foo()
...:
in foo()
In [44]:
In [44]: import time
In [45]: def foo():
...: start = time.clock()
...: print('in foo()')
...: end = time.clock()
...: print('used:', end - start)
...: foo()
...:
in foo()
used: 2.1999999997746045e-05
In [46]:
装饰器进阶
### 练习1
In [46]: import time
In [47]: def foo():
...: print('in foo()')
...: def timeit(func):
...: start = time.clock()
...: func()
...: end = time.clock()
...: print('used:', end-start)
...: timeit(foo)
...:
in foo()
used: 2.2999999998774e-05
In [48]:
### 练习2
In [48]: import time
In [49]: def foo():
...: print('in foo()')
...: def timeit(func):
...: def wrapper():
...: start = time.clock()
...: func()
...: end = time.clock()
...: print('used:', end - start)
...: return wrapper
...: foo=timeit(foo)
...: foo()
...:
in foo()
used: 0.00010500000000490672
In [50]:
### 练习3
In [57]: def document_it(func):
...: def new_function(*args, **kwargs):
...: print('Running function:', func.__name__)
...: print('Postitional arguments:', args)
...: print('Keyword arguments:', kwargs)
...: result = func(*args, **kwargs)
...: print('document_it Result:', result)
...: return result
...: return new_function ##闭包
...:
In [58]: def add_ints(a, b):
...: return a + b
...:
### 手动应用装饰器
In [59]: cooler_add_ints = document_it(add_ints)
In [60]: cooler_add_ints(3, 5)
Running function: add_ints
Postitional arguments: (3, 5)
Keyword arguments: {}
document_it Result: 8
Out[60]: 8
In [61]:
### 使用装饰器名字来装饰函数(语法糖)
In [61]: @document_it
...: def add_ints(a, b):
...: return a + b
...:
In [62]: add_ints(3, 5)
Running function: add_ints
Postitional arguments: (3, 5)
Keyword arguments: {}
document_it Result: 8
Out[62]: 8
In [63]:
python 语法糖
In [51]: def timeit(func):
...: def wrapper():
...: start = time.clock()
...: func()
...: end = time.clock()
...: print('used:', end-start)
...: return wrapper
...: @timeit
...: def foo():
...: print('in foo()')
...: foo()
...:
in foo()
used: 2.2999999998774e-05
In [52]:
function模块
In [53]: import time
In [54]: from functools import wraps
In [55]: def timeit(func):
...: @wraps(func)
...: def wrapper():
...: start = time.clock()
...: func()
...: end = time.clock()
...: print('used:', end - start)
...: return wrapper
...: @timeit
...: def foo():
...: print('in foo()')
...: foo()
...: print(foo.__name__)
...:
in foo()
used: 2.2999999998774e-05
foo
In [56]: