只计算一次属性并多次使用结果(不同的方法)

Edu*_*rdo 7 python properties class-method

我试图多次使用类方法的结果,而不进行获得结果所需的繁重计算。

我看到以下选项。你认为哪些是正确的,或者更像 Pythonic?

每一种的优点和缺点是什么?

尝试/除外方法

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    def new_method(self):
        try:
            return self._new_property
        except AttributeError:
            # do some heavy calculations
            return self._new_property
Run Code Online (Sandbox Code Playgroud)

lru_cache 方法

from functools import lru_cache

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    @lru_cache()
    def new_method(self):
        # do some heavy calculations
        return self._new_property
Run Code Online (Sandbox Code Playgroud)

Django 的 cache_property 方法

from django.utils.functional import cached_property

class Test:
    def __init__(self, *args):
        # do stuff

    @cached_property
    def new_method(self):
        # do some heavy calculations
        return self._new_property
Run Code Online (Sandbox Code Playgroud)

Mar*_*oma 11

Python 3.8 更新:您现在可以使用functools.cached_property

from functools import cached_property

class Test:
    def __init__(self, *args):
        # do stuff

    @cached_property
    def new_method(self):
        # do some heavy calculations
        return self._new_property
Run Code Online (Sandbox Code Playgroud)

  • 文档中值得一提的是:“‘cached_property()’的机制与‘property()’有些不同。常规的‘property’会阻止属性写入,除非定义了设置器。相反,‘cached_property’允许写入。 ” 因此在这方面,答案与问题中提出的一些替代方案不同 (2认同)