gpt4 book ai didi

对象中的 Python 缓存

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:11 26 4
gpt4 key购买 nike

我创建了一个名为“Frame”的对象

class Frame:
def __init__(self, image):
self.image = image

def gray(self):
return cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)

一些操作,例如gray(),很昂贵。我想将结果缓存在实例中,以便后续调用不必重新计算它。最干净的方法是什么?

最佳答案

金字塔使用 this fantastic @reify decorator :

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

文档字符串不言自明。 =)

关于对象中的 Python 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23116234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com