python限制函数调用次数
2017-04-24 本文已影响280人
俊杰的笔记
使用注解实现。注解可以是函数,也可以是类的实例。只要是可调用的即可。
# encoding:utf-8
class CallTimesLimit(object):
def __init__(self, max):
print "init CallTimesLimit"
self.__max = max
self.__count = 0
def __call__(self, fun):
print "call __call__"
self.__fun = fun
return self.__proxy
def __proxy(self, *args, **kwargs):
print "proxy"
self.__count += 1
if self.__count > self.__max:
print "adsfasdfasdf"
raise Exception("{f} is called over {limit} times".format(f=self.__fun.__name__,
limit=self.__max))
else:
self.__fun(*args, **kwargs)
@CallTimesLimit(3)
def foo(x):
print x
if __name__ == '__main__':
foo(2)
foo(2)
foo(2)
foo(3)