python闭包应用之装饰器-缓存计算
def decorator(func): dic = {} print(dic, '....') def wrapper(*args): if args in dic: print(f'no calculator, dic ={dic}') return dic[args] value = func(*args) dic[args] = value print(f'calculator, dic = {dic}') return func(*args) return wrapper @decorator def add(a, b, c): return a + b + c print(add(1, 2, 3)) print(add(1, 2, 3)) print(add(4, 5, 6)) print(add(4, 5, 6))
{} ....
calculator, dic = {(1, 2, 3): 6}
6
no calculator, dic ={(1, 2, 3): 6}
6
calculator, dic = {(1, 2, 3): 6, (4, 5, 6): 15}
15
no calculator, dic ={(1, 2, 3): 6, (4, 5, 6): 15}
15
学习开心就好