sentences = ['When I was about eleven or twelve I set up a lab in my house.',
'It consisted of an old wooden packing box that I put shelves in.',
'I had a heater, and I’d put in fat and cook french-fried potatoes all the time.',
'I also had a storage battery, and a lamp bank.']
from functools import wraps
from datetime import datetime
def log_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print(f'[{datetime.now().isoformat()}] Before calling {f.__name__}()')
result = f(*args, **kwargs)
print(f'[{datetime.now().isoformat()}] After {f.__name__}() called')
return result
return wrapper
@log_decorator
def factorial(n):
result = 1
for i in range(n):
result = result * (i+1)
return result
factorial(10)
[2019-11-27T18:41:16.042448] Before calling factorial()
[2019-11-27T18:41:16.042542] After factorial() called
3628800
import sys
l = [i for i in range(10000) if i % 3 == 0 or i % 5 == 0]
print(sys.getsizeof(l)) # => 38224
g = (i for i in range(10000) if i % 3 == 0 or i % 5 == 0)
print(sys.getsizeof(g)) # => 128
0. 概述
1. 副作用
2. 纯函数
3. 函数也是数据
4. 常用高阶函数
4.1 map
我们看看例子:
[-2, -1, 0, 1, 2]
->[abs(-2), abs(-1), abs(0), abs(1), abs(2)]
->[2, 1, 0, 1, 2]
4.2 reduce
map
reduce
很重要而且经常一起出现呢?4.3 filter
4.4 partial
5. 函数装饰器
5.1 处理被装饰函数的参数
5.2 带参数的装饰器
5.3 装饰器类
5.4 装饰器的价值
装饰器不仅是一种漂亮的语法糖,它实质上是一种特殊的函数抽象方法,非常有助于我们书写纯函数(pure functions)。
我们前面讲了 pure function 的好处,简单内聚,无副作用,但有些事情不可避免的需要副作用,比如前面举例的想要统计函数调用的次数和时间,想给函数调用前后加上日志记录,或者在函数调用前检查是否拥有访问的权限,等等,这些操作都需要在函数中检查某个外部状态,或者改变某个全局变量的值。
类似这些日志啊、权限检查啊,与函数主体目标没有直接联系但又不得不做的全局性功能,有一个术语叫 cross-cutting concerns,即 “横切式” 的功能,而装饰器就是解决这类问题的良药。
装饰器把这些 cross-cutting concerns 抽离出来写在 decorator 中,保持原函数仍聚焦于自己的核心目标,这样就做到了概念责任分离(separation of concerns)。
这样子一来,程序中大部分函数可以是纯的,而一些麻烦的、不得不依赖副作用的全局 cross-cutting concerns 可以在少量 decorator 中处理。
另外,有些应用框架大量采用 decorator 来实现模板化的编程,我们后面会学到的 Web 应用开发框架 Flask 就是一个典型的例子。
6 惰性计算
range()
7. 小结
Logging
2020-04-26 01:18:15 3rd review 2020-04-24 17:52:55 2nd review 2020-04-20 12:36:21 initialize