我遵循以下约定来修饰Python类中的某些方法。我想知道是否有更好的方法来做同样的事情。我的方法看起来确实不太好;对原始成员函数的调用看起来一点也不直观。你知道吗
from threading import Lock
def decobj(fun):
def fun2(*args, **kwards):
with args[0].lock:
print 'Got the lock'
fun(*args, **kwards)
return fun2
class A:
def __init__(self, a):
self.lock = Lock()
self.x = a
pass
@decobj
def fun(self, x, y):
print self.x, x, y
a = A(100)
a.fun(1,2)
如果您的decorator只能处理方法(因为您需要访问实例特定的锁),那么只需在包装签名中包含
self
:我包含了^{} utility decorator ;它将跨多个元数据片段从原始包装函数复制到包装器。这总是个好主意。你知道吗
相关问题 更多 >
编程相关推荐