高阶函数
凡是操作其他函数的函数都叫高阶函数, 不管是将其他函数当做参数, 还是返回一个新的函数
函数作为参数
类似 js 中的回调函数
python
def double(x):
return x * 2
items = map(double, [1, 3, 5, 7]) # 遍历 list 并返回 map object
items = list(items) # 将 map 再转 list
print(items) # [2, 6, 10, 14]
返回一个函数
python
# 函数缓存
def memoize(fn):
caches = {}
def memoized_func(*args):
nonlocal caches # 这个 caches 会一直被引用不会释放
key = f"{args}"
cache = caches.get(key)
if(cache):
print("result from cache")
return cache
else:
val = fn(*args)
caches[key] = val
return val
return memoized_func
def sum(x, y):
print(f"sum is called with {x},{y}")
return x + y
lazy_sum = memoize(sum)
lazy_sum(1, 2)
lazy_sum(1, 2)
lazy_sum(1, 2)
lazy_sum(1, 2)
lazy_sum(1, 2)
lazy_sum(3, 4)
lazy_sum(3, 4)
lazy_sum(3, 4)
lazy_sum(3, 4)
lazy_sum(3, 4)
lazy_sum(3, 4)
装饰器
python
# 装饰器本质上就是一个返回函数的高阶函数
def log(func):
# 被 log 装饰的函数会输出被调用的信息
def wrapper(*args, **kw):
from time import gmtime, strftime, time as timestamp
start_time = timestamp()
result = func(*args, **kw) # exec
end_time = timestamp()
used_time = end_time - start_time
call_at = strftime("%Y-%m-%d %H:%M:%S", start_time)
print(f"{func.__name__}() is called at [{call_at}]")
print(f"\targs : {args}")
print(f"\tkwargs : {kw}")
print(f"\ttime_info: start_time:{start_time} end_time:{end_time} used_time:{used_time}")
print(f"\tresult : {result}")
print("---"*30)
return result
return wrapper
@log
def sum(x:int, y:int):
# 为了看到效果
import time
time.sleep(2)
return x + y
sum(1, 2)
sum(3, 4)