【问题标题】:Python property decorator and expensive computationsPython 属性装饰器和昂贵的计算
【发布时间】:2020-10-27 21:03:46
【问题描述】:

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

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

所以我只是使用:

@property
def element(self):
    ...

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

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

【问题讨论】:

标签: python properties decorator


【解决方案1】:

functools 模块有一个内置的装饰器来执行此操作。它被称为cached_property。这是来自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)

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多