提问者:小点点

Python属性修饰器和昂贵的计算


我通常使用@property来避免以下情况:

def __init__(self, ...):
    self.element = self._getElement()

因此我只需使用:

@property
def element(self):
    ...

但是,当修饰函数执行昂贵的计算时,这就不太方便了,而且如果self.element被以多种方式调用,那么就会为每个调用执行计算。

有没有一种方法可以避免这种情况,也许是存储计算结果? 还是我只是用错了@property?


共1个答案

匿名用户

functools模块有一个内置的装饰器来完成这个任务。 它称为cached_property。 下面是Python文档中的一个示例。

from functools import cached_property

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)

    @cached_property
    def variance(self):
        return statistics.variance(self._data)