装饰 Python class 方法的最佳方式是什么?

What is the best way to decorate methods of a Python class?

我遵循以下约定来修饰 Python class 中的某些方法。我想知道是否有更好的方法来做同样的事情。我的方法肯定不好看;对原始成员函数的调用看起来一点也不直观。

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)

如果您的装饰器只能处理方法(因为您需要访问特定于实例的锁),那么只需在包装器签名中包含 self

from functools import wraps

def decobj(func):
    @wraps(func)
    def wrapper(self, *args, **kwards):
        with self.lock:
            print 'Got the lock'
            func(self, *args, **kwards)
    return wrapper

我包括了@functools.wraps() utility decorator;它将跨各种元数据从原始包装函数复制到包装器。这总是一个好主意。