Python语言与信息数据获取和机器学习Python 运维大数据 爬虫Python AI Sql

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

2017-09-01  本文已影响0人  我有一只碗

装饰器算是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
上一篇下一篇

猜你喜欢

热点阅读