问题描述
我正在用python写一个类,并且我有一个属性,该属性将花费相对较长的时间来计算,所以我只想做一次.此外,该类的每个实例都不需要使用它,因此我不想在__init__
中默认使用.
我是Python的新手,但不熟悉编程.我可以想出一种很容易做到这一点的方法,但是我一遍又一遍地发现,"Pythonic"做事的方法通常比我在其他语言中的经验要简单得多. >
在Python中是否有正确"的方法来实现此目的?
Python≥3.2
您应该同时使用 @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)
或者其他提到的任何实现都可以满足您的需求.
或上述反向端口.
I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so I only want to do it once. Also, it will not be needed by every instance of the class, so I don't want to do it by default in __init__
.
I'm new to Python, but not to programming. I can come up with a way to do this pretty easily, but I've found over and over again that the 'Pythonic' way of doing something is often much simpler than what I come up with using my experience in other languages.
Is there a 'right' way to do this in Python?
Python ≥ 3.2
You should use both @property
and @functools.lru_cache
decorators:
import functools
class MyClass:
@property
@functools.lru_cache()
def foo(self):
print("long calculation here")
return 21 * 2
This answer has more detailed examples and also mentions a backport for previous Python versions.
Python < 3.2
The Python wiki has a cached property decorator (MIT licensed) that can be used like this:
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)
Or any implementation mentioned in the others answers that fits your needs.
Or the above mentioned backport.
这篇关于在Python中缓存类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!