filter –>map –>  reduce
过滤       映射       归约
过滤      映射     
| 12
 3
 4
 5
 6
 7
 8
 
 | a =[12, 95, 88, 45]sum([x**x for x in a if x % 2])
 
 
 fn = lambda x,y :x**y
 def foo():
 pass
 fn =foo
 
 | 
在python中函数式一等对象(一定公民)
- 函数可以赋值给变量
- 函数可以作为函数的参数   —>fillter
- 函数可以作为函数的返回值 —>装饰器
函数参数:
- 位置参数 
- 可变参数 -tuple 
- 关键字参数 - dict 
- 命名关键字参数 
自定义装饰器 - 装饰函数 / 装饰类  –设计模式(代理模式)
代理模式
用代理对象(装饰器函数)去执行被代理对象(被装饰的函数)的行为
面向切面编程 —AOP
在程序中跟正常业务逻辑没有必然联系而且会重复使用的功能通常被称为横切关注功能,这种横切关注功能不应该写在业务逻辑代码是上,而应该使用装饰器或中间件来完成
指令式编程(汇编语言) /过程式语言(c语言)
Python既支持面向对象编程,也支持函数式编程
一条语句求阶乘
| 1
 | fn = lambda n: functools.reduce(int.__mul__, range(1,n+1))
 | 
heapq内置模块  提供基于堆的优先排序算法
| 12
 3
 4
 
 | import heapqlist1[1,4,5,63,24]
 heapq.nsmallest(list1,n)
 heapq.nlargest(list1,3)
 
 | 
全排列
| 12
 3
 
 | import itertoolsfor val in itertools.combinations('abcde', 3):
 print (val)
 
 | 
笛卡尔积
| 12
 
 | for val in itertools.product('ABCD',123):print(val)
 
 | 
装饰器
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | from functools import wrapsdef record(func):
 @wraps(func)
 def wrapper(*args, **kwargs):
 
 ret_value = func(*args, *kwargs)
 return ret_value
 
 return wrapper
 
 | 
带参数的装饰器
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 
 | import timefrom functools import wraps
 from random import randint
 
 def record_time(output):
 
 def func(function):
 
 
 @wraps(function)
 def timeCount(*args, **kwargs):
 timestart = time.time()
 result = function(*args, **kwargs)
 timesend= time.time()
 output(function.__name__, timesend - timestart)
 return result
 return timeCount
 
 return func
 
 def log_to_file(fn, duration):
 with open('result.txt', 'a')as fs:
 fs.write('%s: %.3f秒\n' %(fn,duration))
 
 
 @record_time(log_to_file)
 def fool():
 time.sleep(randint(1,3))
 
 
 def main():
 for _ in range(5):
 
 fool()
 
 foo2 = fool.__wrapped__
 for _ in range(3):
 
 foo2()
 
 
 
 if __name__ == '__main__':
 main()
 
 |