python - 在Python中动态应用setter装饰器

标签 python python-3.x python-decorators

我正在寻找一种方法来编写包装属性和 setter 装饰器的装饰器。理想情况下,此装饰器将执行一些简单的工作,然后返回用 @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)

取决于什么是合适的和/或更清晰的

关于python - 在Python中动态应用setter装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846245/

相关文章:

Python 请求开始从检查点下载文件

python - 有没有更优雅的方法来过滤函数的失败结果?

python - 分隔特定列并将它们添加为 CSV 中的列(Python3、CSV)

python - 如何过滤一列中在另一列中具有公共(public)值的两个特定值

python - 如何加速numpy张量*张量运算

python - Pip 不适用于 Ubuntu 上的 Python 3.10

python - 使用装饰器链在程序退出时注册类方法

python - 向 kwargs 添加参数时出错

python - 使用装饰器调用不带参数的函数

python - 如何在排序列表中对具有相似开头的字符串进行分组?