python计算多次_Python – 只计算一次属性并多次使用结果(不同的方法)
我試圖多次使用類方法的結果而不進行獲得結果所需的繁重計算.
我看到以下選項,您認為哪些是正確的,或更多的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计算多次_Python – 只计算一次属性并多次使用结果(不同的方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python作业是什么意思_Python
- 下一篇: websocket python爬虫_p