【发布时间】:2025-12-08 21:10:02
【问题描述】:
我尝试多次使用类方法的结果,而不进行获得结果所需的繁重计算。
我看到以下选项。你认为哪个是正确的,还是更 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
【问题讨论】:
-
好问题。 Related SO question 强烈支持 lru_cache。因为你不使用任何参数,直觉上,我会继续使用普通的 try-catch。
-
这能回答你的问题吗? Caching class attributes in Python
标签: python properties class-method