我想用Python做一点事情,类似于内置的property
,但我不确定该怎么做。
我称此类为LazilyEvaluatedConstantProperty
。它用于仅应计算一次且不会更改的属性,但是为了提高性能,应该懒惰地创建它们,而不是在对象创建时创建它们。
这是用法:
class MyObject(object):
# ... Regular definitions here
def _get_personality(self):
# Time consuming process that creates a personality for this object.
print('Calculating personality...')
time.sleep(5)
return 'Nice person'
personality = LazilyEvaluatedConstantProperty(_get_personality)
您可以看到用法与
property
相似,只不过有一个getter,没有setter或Deleter。目的是在第一次访问
my_object.personality
时,将调用_get_personality
方法,然后将结果缓存,并且永远不会再次为此对象调用_get_personality
。我实现这个有什么问题?我想做一些棘手的事情来提高性能:我希望在第一次访问和
_get_personality
调用之后,personality
将成为对象的数据属性,因此在后续调用中查找会更快。但是我不知道怎么可能,因为我没有对该对象的引用。有人有主意吗?
最佳答案
我实现了它:
class CachedProperty(object):
'''
A property that is calculated (a) lazily and (b) only once for an object.
Usage:
class MyObject(object):
# ... Regular definitions here
def _get_personality(self):
print('Calculating personality...')
time.sleep(5) # Time consuming process that creates personality
return 'Nice person'
personality = CachedProperty(_get_personality)
'''
def __init__(self, getter, name=None):
'''
Construct the cached property.
You may optionally pass in the name that this property has in the
class; This will save a bit of processing later.
'''
self.getter = getter
self.our_name = name
def __get__(self, obj, our_type=None):
if obj is None:
# We're being accessed from the class itself, not from an object
return self
value = self.getter(obj)
if not self.our_name:
if not our_type:
our_type = type(obj)
(self.our_name,) = (key for (key, value) in
vars(our_type).iteritems()
if value is self)
setattr(obj, self.our_name, value)
return value
对于将来,可以在以下位置找到维护的实现:
https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/caching/cached_property.py