在 Python 中动态应用 setter 装饰器

Dynamically applying setter decorator in Python

我正在寻找一种方法来编写包装 属性 和 setter 装饰器的装饰器。理想情况下,这个装饰器将执行一些简单的工作,然后 return 用 @property@propertyname.setter 装饰的方法版本。我正在为 @property 想象这样的事情,但想不出一种表达方式:

def my_property_decorator(func):
    def decorator(*args):
        # do some work here

        # apply regular property decorator
        @property(func) # this is not correct syntax
        return func(*args)

    return decorator

对于setter,我更茫然了,因为我必须得到被装饰的属性的名字,才能组成装饰者的全名,但是我我不确定当我将其名称作为字符串时我将如何应用装饰器。

我想我可以像这样堆叠装饰器:

@property
@my_property_decorator
def prop(self):
    # implementation


@prop.setter
@my_setter_decorator
def prop(self, newVal):
    # implementation

但想看看是否有我没有看到的更清洁的解决方案。

请注意,装饰器只是标准的 Python 对象,即主要是 类 和函数。还记得:

@decorator
def foo():
  pass

只是

的缩写
def foo():
  pass
foo = decorator(foo)

因此您可以像这样编写代码:

def my_property_decorator(func):
    @property
    def decorator(*args):
        # do some work here
        return func(*args)
    return decorator

或喜欢:

def my_property_decorator(func):
    func = property(func)
    def decorator(*args):
        # do some work here
        return func(*args)
    return decorator

甚至:

def my_property_decorator(func):
    def decorator(*args):
        # do some work here
        return func(*args)
    return property(decorator)

取决于什么是合适的and/or更清晰