您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中缓存类属性

在Python中缓存类属性

@property@functools.lru_cache已合并为@cached_property

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

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

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

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

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)

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

python 2022/1/1 18:35:07 有228人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶