装饰器习题

1.命令分发器

输入命令映射到一个函数,并执行这个函数,如果输入了某个cmd命令后没找到函数,就要调用缺省的函数执行,这正好是字典缺省参数.

def dispatche():
    dict1 = {}

    def reg(name):   #注册函数
        def _reg(fn):
            dict1[name] = fn
            return fn
        return _reg

    def default1():	 #缺省函数
        print('No')

    def find1():	 #找到对应的函数
        while True:
            x = input('>>>')
            if x.strip() == '':
                break
            dict1.get(x,default1)()
    return reg,find1
reg,find1=dispatche()

@reg('xxxx')
def foo1():
    print('1')
@reg('yyyy')
def foo2():
    print('2')

find1()  

2.实现缓存功能的装饰器,并且实现定期删除功能

定义一个加法函数
1:add(4,5)
2:add(4,y=5)
3:add(y=5,x=4)
4:add(x=4,y=5)
lru_cache实现了1,2,3,4各不同的缓存
①先完成全部相同的缓存

import inspect
from functools import wraps

def cache3(fn):
    cache_big = {}
    @wraps(fn)
    def _cache3(*args,**kwargs):
        sign = inspect.signature(fn)
        params = sign.parameters

        cache_dict = {}
        cache_dict.update(zip(params.keys(),args),**kwargs)

        # for k,v in params.items():
        #     if k not in cache_dict.keys():
        #         cache_dict[k] =v.default
        cache_dict.update((k,params[k].default) for k in (params.keys() - cache_dict.keys()))
        #cache_dict.update(((k,v.default) for k,v in params.items() if k not in cache_dict.keys()))

        keys = tuple(sorted(cache_dict.items()))
        if keys not in cache_big.keys():
            cache_big[keys] = fn(*args,**kwargs)

        return cache_big[keys]
    return _cache3


import time
@cache3
def add3(x=3,y=4):
    time.sleep(3)
    return x+y


print(add3(x=3,y=4))
print('111111111')
print(add3(3,4))

②添加时间戳,清除过期数据

import inspect
from functools import wraps
import datetime
import time
def cache3(duration = 5):
    def _cache3(fn):
        cache_big = {}
        @wraps(fn)
        def _1cache3(*args,**kwargs):


            now = datetime.datetime.now().timestamp()
            # for k,(_,v) in  cache_big.items():
            #     if now - v >duration:
            #         expire_keys.append(k)
            for k in [k for k,(_,v) in  cache_big.items() if now - v >duration]:
                cache_big.pop(k)


            sign = inspect.signature(fn)
            params = sign.parameters
            cache_dict = {}
            cache_dict.update(zip(params.keys(),args),**kwargs)

            # for k,v in params.items():
            #     if k not in cache_dict.keys():
            #         cache_dict[k] =v.default
            cache_dict.update((k,params[k].default) for k in (params.keys() - cache_dict.keys()))
            #cache_dict.update(((k,v.default) for k,v in params.items() if k not in cache_dict.keys()))

            keys = tuple(sorted(cache_dict.items()))
            if keys not in cache_big.keys():
                cache_big[keys] = fn(*args,**kwargs),datetime.datetime.now().timestamp()

            return cache_big[keys]
        return _1cache3
    return _cache3


import time
@cache3()
def add3(x=3,y=4):
    time.sleep(3)
    return x+y


print(add3(x=3,y=4))
print('111111111')
time.sleep(4)
print(add3(3,4))

③把不同功能的模块抽离出来,因为每次运行都要重新定义函数

import inspect
from functools import wraps
import datetime
import time


def _clear_expires(cache_big, duration):                      #抽出来一个
    now = datetime.datetime.now().timestamp()
    for k in [k for k, (_, v) in cache_big.items() if now - v > duration]:
        cache_big.pop(k)
def cache3(duration = 5):
    def _cache3(fn):
        cache_big = {}
        @wraps(fn)
        def _1cache3(*args,**kwargs):


            _clear_expires(cache_big,duration)


            sign = inspect.signature(fn)                     #这个功能怎么抽离出来呢????
            params = sign.parameters
            cache_dict = {}
            cache_dict.update(zip(params.keys(),args),**kwargs)
            cache_dict.update((k,params[k].default) for k in (params.keys() - cache_dict.keys()))
            keys = tuple(sorted(cache_dict.items()))


            if keys not in cache_big.keys():
                cache_big[keys] = fn(*args,**kwargs),datetime.datetime.now().timestamp()

            return cache_big[keys]
        return _1cache3
    return _cache3


import time
@cache3()
def add3(x=3,y=4):
    time.sleep(3)
    return x+y


print(add3(x=3,y=4))
print('111111111')
time.sleep(4)
print(add3(3,4))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值