Geo*_*Geo 6 python language-features decorator
我想编写一个限制函数执行次数的装饰器,具体方法如下:
@max_execs(5)
def my_method(*a,**k):
# do something here
pass
Run Code Online (Sandbox Code Playgroud)
我认为写这种类型的装饰器是可能的,但我不知道如何.我认为一个函数不会是这个装饰者的第一个参数,对吗?我想要一个"普通的装饰器"实现,而不是一些带有调用方法的类.
这样做的原因是要了解它们的编写方式.请解释语法,以及该装饰器的工作原理.
mip*_*adi 12
这是我掀起的.它不使用类,但它确实使用函数属性:
def max_execs(n=5):
def decorator(fn):
fn.max = n
fn.called = 0
def wrapped(*args, **kwargs):
fn.called += 1
if fn.called <= fn.max:
return fn(*args, **kwargs)
else:
# Replace with your own exception, or something
# else that you want to happen when the limit
# is reached
raise RuntimeError("max executions exceeded")
return wrapped
return decorator
Run Code Online (Sandbox Code Playgroud)
max_execs返回一个被调用的函数decorator,然后返回wrapped.decoration将max execs和当前exec数存储在两个函数属性中,然后将其签入wrapped.
翻译:使用这样的装饰器时:
@max_execs(5)
def f():
print "hi!"
Run Code Online (Sandbox Code Playgroud)
你基本上是这样做的:
f = max_execs(5)(f)
Run Code Online (Sandbox Code Playgroud)