Python ≥ 3.8
@property
に@functools.lru_cache
統合されてい@cached_property
ます。
import functools
class MyClass:
@functools.cached_property
def foo(self):
print("long calculation here")
return 21 * 2
Python ≥ 3.2 < 3.8
@property
と@functools.lru_cache
デコレータの両方を使用する必要があります。
import functools
class 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 class
class 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)
または、ニーズに合った他の回答で言及されている実装。
または上記のバックポート。