繁体   English   中英

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

[英]Python property decorator and expensive computations

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

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

所以我只需使用:

@property
def element(self):
    ...

然而,当修饰的 function 执行昂贵的计算时,这不是很方便,并且如果 self.element 在许多部分和不同的方式中被调用,那么计算将针对每个单独的调用执行。

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM