python - 在 Python 中缓存类属性

标签 python memoization

我正在用 python 编写一个类,并且我有一个需要相对较长时间来计算的属性,所以 我只想做一次。此外,类的每个实例都不需要它,所以 我不想在 __init__ 中默认这样做

我是 Python 新手,但不是编程新手。我可以很容易地想出一种方法来做到这一点,但我一遍又一遍地发现,做某事的“Pythonic”方法通常比我使用其他语言的经验想出的方法简单得多。

在 Python 中是否有“正确”的方法来做到这一点?

最佳答案

3.8 ≤ Python @property@functools.lru_cache已合并为 @cached_property .

import functools
class MyClass:
    @functools.cached_property
    def foo(self):
        print("long calculation here")
        return 21 * 2

3.2 ≤ Python < 3.8

您应该同时使用 @property@functools.lru_cache装饰器:

import functools
class MyClass:
    @property
    @functools.lru_cache()
    def foo(self):
        print("long calculation here")
        return 21 * 2

This answer有更详细的示例,还提到了以前 Python 版本的反向移植。

Python < 3.2

Python wiki 有一个 cached property decorator (MIT 许可)可以这样使用:

import random
# the class containing the property must be a new-style class
class MyClass(object):
   # create property whose value is cached for ten minutes
   @cached_property(ttl=600)
   def randint(self):
       # will only be evaluated every 10 min. at maximum.
       return random.randint(0, 100)

或其他答案中提到的任何满足您需求的实现。
或者上面提到的backport。

关于python - 在 Python 中缓存类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4037481/

相关文章:

python - pandas 将索引值转换为小写

python - 在深度复制期间防止引用重用

python - 使用 functools.lru_cache 时最大递归深度更快达到

python - 如何禁止 PyCharm 在启动时自动更新 Python 解释器

python - 多维张量切片

python - 安装 Python 请求

python - 让 Django 为 MySQL 后端创建外键

javascript - 这个闭包中的参数是在哪一点传递的?

javascript - 无法清除 Javascript Memoized 函数缓存

java - 在java中使用递归方法进行内存