gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:43:12 25 4
gpt4 key购买 nike

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

我看到以下选项。您认为哪些是正确的,或者更 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

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

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

最佳答案

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

关于python - 只计算一次属性并多次使用结果(不同的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com