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

2024-03-29 05:44:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我遵循以下约定来修饰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)

Tags: 方法函数selflockdefargs成员事情
1条回答
网友
1楼 · 发布于 2024-03-29 05:44:22

如果您的decorator只能处理方法(因为您需要访问实例特定的锁),那么只需在包装签名中包含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

我包含了^{} utility decorator;它将跨多个元数据片段从原始包装函数复制到包装器。这总是个好主意。你知道吗

相关问题 更多 >