【问题标题】:What is the best way to decorate methods of a Python class?装饰 Python 类的方法的最佳方法是什么?
【发布时间】:2015-08-08 04:33:13
【问题描述】:

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

【问题讨论】:

  • 为什么你觉得你的方法看起来不太好?如果您只是装饰方法,为什么不将self 添加到包装器签名中?
  • @MartijnPieters 对原始成员函数的调用看起来一点也不直观。所以,我认为会有更好的方法。
  • 如果您对 Python 的一元 *** 运算符感到满意,它看起来不错。在您使用几次之前,有些结构看起来很奇怪

标签: python methods decorator


【解决方案1】:

如果您的装饰器只能处理方法(因为您需要访问特定于实例的锁),那么只需在包装器签名中包含 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;它会将各种元数据从原始包装函数复制到包装器。这总是一个好主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2013-06-18
    • 2018-07-14
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多