Python 对象中的缓存
我创建了一个叫做'Frame'的对象。
class Frame:
def __init__(self, image):
self.image = image
def gray(self):
return cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
有些操作,比如gray(),计算起来比较耗费资源。我想把结果存储在这个对象里,这样以后再调用的时候就不用重新计算了。有什么简单的方法可以做到这一点呢?
3 个回答
0
这是不是可以在创建的时候直接搞定呢?
class Frame:
def __init__(self, image):
self.image = image
self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
补充一下 - 现在看起来是个设置属性的好时机?
class Frame(object):
def __init__(self, image):
self.image = image
self._grey = None
@property
def grey(self):
if self._grey is None:
self._grey = solve_for_grey(self.image, stuff)
return self._grey
2
解决这类问题的最佳方法是使用一种叫做“记忆化”的函数,这是一种简单的装饰器解决方案。你可以在这里找到相关的内容:(http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/)
4
Pyramid使用了一个很棒的@reify装饰器:
class reify(object):
""" Use as a class method decorator. It operates almost exactly like the
Python ``@property`` decorator, but it puts the result of the method it
decorates into the instance dict after the first call, effectively
replacing the function it decorates with an instance variable. It is, in
Python parlance, a non-data descriptor. An example:
.. code-block:: python
class Foo(object):
@reify
def jammy(self):
print('jammy called')
return 1
And usage of Foo:
>>> f = Foo()
>>> v = f.jammy
'jammy called'
>>> print(v)
1
>>> f.jammy
1
>>> # jammy func not called the second time; it replaced itself with 1
"""
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except: # pragma: no cover
pass
def __get__(self, inst, objtype=None):
if inst is None:
return self
val = self.wrapped(inst)
setattr(inst, self.wrapped.__name__, val)
return val
文档说明得很清楚。=)