Python 记忆装饰器

Python 记忆装饰器,python,Python,我有以下伪代码: class myClass() def slow_method(self): try: return self.memo_slow_method except: self.memo_slow_method = some_slow_function() return self.memo_slow_method 有没有可能构建一个记忆装饰器来执行这个逻辑 限制: 虽然memo\u slow\u方法不需

我有以下伪代码:

class myClass()
  def slow_method(self):
     try:
         return self.memo_slow_method
     except:
         self.memo_slow_method = some_slow_function()
         return self.memo_slow_method
有没有可能构建一个记忆装饰器来执行这个逻辑

限制:

  • 虽然memo\u slow\u方法不需要直接访问,但它必须在对象上定义,以便在清除对象本身时将其清除-非常重要
  • <> LI>不需要考虑除<代码>自身< /代码>以外的参数-任何参数都不会被传递。

PS我一直在使用@lrucache,但它不适合我的用途。它确实需要严格遵循上述逻辑。

您可以使用描述符(类似于属性)而不是装饰器:

然后设置描述符:

class Fun(object):
    meth = Memoize('x', lambda: print('in') or 10)
然后交互测试:

>>> f = Fun()
>>> f.meth  # function is executed
'in'
10
>>> f.x
10
>>> f.meth  # function is not executed
10
如果你真的想要一个装饰师:

def memoize(func):
    def inner(self):
        try:
            return self.memo_slow_method   # hardcoded memo attribute name
        except:
            self.memo_slow_method = func(self)  # execute the method body
            return self.memo_slow_method
    return inner

class Fun(object):
    @memoize
    def meth(self):
        print('in')
        return 100

>>> f = Fun()
>>> f.meth()
'in'
100
>>> f.meth()
100
>>> f.memo_slow_method
100

这里有一个decorator,它完全按照要求实现您的逻辑。 它通过添加前缀从函数名(可在
func.\uuuuuu name\uuuuu
中找到)中获得备注字段的名称:

from __future__ import print_function
import time
from functools import wraps

memo_prefix = '_memo_' # Check for possible name collision

def deco(func):
    memo_field_name = memo_prefix + func.__name__

    def ret_func(self):
        try:
            return getattr(self, memo_field_name)
        except AttributeError:
            ret_val = func(self)
            setattr(self, memo_field_name, ret_val)
            return ret_val
    return ret_func

def some_slow_function():
    for x in range(3):
        time.sleep(1)
        print('Waiting...', x)
    return 'Done'

class myClass():
    @deco
    def slow_method(self):
        return some_slow_function()
现在测试它:

In [2]: it = myClass()

In [3]: print(it.slow_method())
Waiting... 0
Waiting... 1
Waiting... 2
Done

In [4]: print(it.slow_method())
Done

In [5]: print(it.__dict__)
{'_memo_slow_method': 'Done'}

有些函数会返回什么?方法还是价值?是否会减慢_方法返回函数?有一个。由于Python 3.2,它包含在标准库中。
In [2]: it = myClass()

In [3]: print(it.slow_method())
Waiting... 0
Waiting... 1
Waiting... 2
Done

In [4]: print(it.slow_method())
Done

In [5]: print(it.__dict__)
{'_memo_slow_method': 'Done'}