Edu*_*rdo 7 python properties class-method
我试图多次使用类方法的结果,而不进行获得结果所需的繁重计算。
我看到以下选项。你认为哪些是正确的,或者更像 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Mar*_*oma 11
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
Run Code Online (Sandbox Code Playgroud)