我想在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
将成为对象的数据属性,因此在后续调用中查找会更快。但我不知道它是如何可能的,因为我没有对象的引用。
有没有人有想法?
答案 0 :(得分:1)
我实施了它:
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
对于未来,可能会在此处找到维护的实施: