带参数的装饰器一般的格式为:
from threading import RLock
def lockhelper(lock):
def _deco(func):
def __deco(*args, **kwargs):
if True == lock.acquire():
try:
ret = func(*args, **kwargs)
except Exception as e:
lock.release()
raise e
lock.release()
return ret
return __deco
return _deco
global_lock = RLock()
@lockhelper(global_lock)
def test(a, b):
print 'test'
print a
print b
return
test(2, 3)
下面我们分析一下它的执行过程:
首先是@的作用:lockhelper(global_lock)(test)(2, 3)
然后发现lockhelper(global_lock)就是_deco
所以就是_deco(test)(2, 3)
然后发现_deco(test)就是__deco
于是转化为:__deco(2, 3)
这就到了装饰器真正执行的函数__deco:
if True == lock.acquire():
try:
ret = func(*args, **kwargs)
except Exception as e:
lock.release()
raise e
lock.release()
这些函数都是内嵌的,所以func=test,lock=global_lock这些变量都传递到了内嵌函数__deco中。
说了这些,还是感觉只可意会,不可言传啊!原来内嵌函数在装饰器中才真正发挥作用。