在Python中缓存类属性

mwolfe02:

我正在用python写一个类,并且我有一个属性,该属性将花费相对较长的时间来计算,因此我只想执行一次此外,它会不会被类的每个实例需要的,所以我不想在默认情况下做到这一点__init__

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

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

Maxime R .:

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

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

Python≥3.2 <3.8

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

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

该答案有更详细的示例,还提到了先前Python版本的反向移植。

Python <3.2

Python Wiki有一个缓存的属性装饰器(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)

或者其他提及的任何实现都可以满足您的需求。
还是上面提到的反向端口。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章