python 闭包(使用装饰器)


https://zhuanlan.zhihu.com/p/44667584

#1 闭包+装饰器
def cache(func):
    amizedata = {}    # 闭包,这个值一直在
    def wrapper(*args, **kwargs):
        key = f'{func.__name__}-{str(args)}-{str(kwargs)})'
        print(amizedata)
        if key in amizedata:
            result = amizedata.get(key)
            print('cached')
        else:
            result = func(*args, **kwargs)
            amizedata[key] = result
            print('calculated')
        return result
    return wrapper

@cache
def rectangle_area(length, width):
    return length * width

rectangle_area(2, 3)
# calculated
# 6

rectangle_area(2, 3) # amizedata = {'rectangle_area-(2, 3)-{})': 6}
# cached 
# 6



#2 普通函数
def rectangle_area2(length, width):
    amizedata = {}   # 不是闭包,这个值销毁
    key = f'{str(length)}-{str(width)})'
    print(amizedata)
    if key in amizedata:
        result = length * width
        print('cached')
    else:
        result = length * width
        amizedata[key] = result
        print('calculated')
    return result

rectangle_area2(2, 3)
# calculated
rectangle_area2(2, 3)   
# calculated

posted @ 2021-03-29 16:16  该显示昵称已被使用了  阅读(33)  评论(0编辑  收藏  举报