Skip to main content
 首页 » 编程设计

python之CPU 密集型的依赖属性

2025年04月02日16tuyile006

我经常遇到这种情况,但没有设法找到一种稳定的处理方式。

假设我有一个这样定义的类:

class MyClass(object): 
    def __init__(self, a, b): 
        self.a = a 
        self.b = b 
 
    @property 
    def c(self): 
       """This method performs some heavy computations based on a and b properties""" 
        # Some heavy computations only with a and b attributes 
        return c 

属性 c 现在可以通过以下方式检索:

>>> obj = MyClass(a, b) 
>>> print obj.c 

但是,每次我请求 obj.c 时,都会执行繁重的计算,导致性能不佳的代码,因为 c 是繁重计算的结果,它会最好仅在设置或修改a或b时计算。

处理这种情况的更好方法是什么?我正在考虑创建一个 c_update 方法来用作某些 @a.setter 和 @b.setter 装饰方法的装饰器,但这是更好的方法?

问候,

请您参考如下方法:

But what if I have a lot of XX dependent properties that rely on a and b values. Do I have to write an update_XX method for each of them and add this method to init and to each a.setter and b.setter ? That seems to me quite verbose...

每次 a 或 b 发生变异时,您都可以更新 c 值(以及任何其他数量的依赖属性),我实现了下面的 update_properties() 方法:

class MyClass(object): 
    def __init__(self, a, b): 
        self._a = a 
        self._b = b 
 
        self.update_properties() 
 
    @property 
    def a(self): 
        return self.a 
 
    @a.setter 
    def a(self, value): 
        self._a = value 
        self.update_properties() 
 
    @property 
    def b(self): 
        return self._b 
 
    @b.setter 
    def b(self, value): 
        self._b = value 
        self.update_properties() 
 
    def update_properties(self): 
        self.c = self._a + self._b 
        self.d = self._a * self._b 
        self.e = self._a - self._b 
        # self.f = ... 
        # ... 
        # self.z = ... 
        # Can go on as long as you want 

Do you think it would be possible to implement this machinery as some decorators in order to lighten the code

冗长似乎只出现在跟踪自由变量的那一边(例如这里的a 和b),所以如果我有为了支持任意数量的那些,我将实现一个 MyClass.set_value(name, value)

def set_value(self, name, value): 
    setattr(self, name, value) 
    self.update_properties() 

所以这里的想法是我们的​​ set_value() 可以处理任意数量的属性。如果您使用 **kwargs 解压传递给构造函数的键值,则可以从 __init__ 调用它。

这里有一个要求,因为我们没有将自由变量设置为 @property,所以我们需要使用 obj.set_value('a', 42) obj.a = 42