栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中缓存类属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中缓存类属性

Python≥3.8

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

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

Python≥3.2 <3.8

您应该同时使用

@property
@functools.lru_cache
装饰器:

import functoolsclass 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 classclass 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)

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633733.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号