使用Python装饰器实现限制函数调用的频率

装饰器算是Python非常有用的特性之一了,因为它实现了DRYC(不要重复你自己的代码),但是它非常难驾驭,十分不好理解。

def doc_it(f):
    def decorator(*args, **kwargs):
        print('This is doc')
        return f(*args, **kwargs)
    return decorator

这就是一个标准的装饰器了,它能在所装饰的函数调用前自动输出一行文本

@doc_it
def func():
    print('a')

上面的代码做的事情就是把func作为参数传入了装饰器doc_it,相当于func=doc_it(func),我们可以得到一个新函数,尽管我们还可以通过func调用它,但是输出一下func._name_发现会得到decorator,说明它确实已经变成了另外一个函数

用这个有用的特性我们可以实现一个函数内部缓存的效果,原理如下:

def count_it(f):
    count = [0]
    def decorator(*args, **kwargs):
        count[0] += 1
        print('count is {count}'.format(count[0]))
        return f(*args, **kwargs)
    return decorator

这个装饰器我们可以轻易统计出一个函数调用的次数,但是我们那个缓存为什么要使用list类型呢,用一个int类型岂不是更好,但是这里只能用可变类型的数据,具体原因参考默认参数。

然后我们用装饰器实现限制函数调用的频率就很简单了

from time import time

def time_required(f):
    last = [time()]
    def decorator(*args, **kwargs):
        if time() - last[0] < 10:
            raise RuntimeError('This time not allow, please wait to {time}'.format(time=last[0] + 10))
        last[0] = time()
        return f(*args, **kwargs)
    return decorator
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容