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

Python property decorator and expensive computations

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

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

所以我只需使用:

@property
def element(self):
    ...

然而,当修饰函数执行昂贵的计算时,这不是很方便,如果 self.element 在许多部分以不同的方式被调用,那么每次调用都会执行计算。

有没有办法避免这种情况,也许存储计算结果?或者我只是以错误的方式使用@属性?

functools module has a built-in decorator to do this. It is called cached_property. Here's an example from the Python docs.

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)