如何以OOP方式为方法分配缓存?

时间:2013-06-27 14:18:48

标签: python memoization

假设我有 A 类,并且此类有一个名为 function 的方法。我可以将缓存指定为此方法的属性吗?从某种意义上说,我可以称之为财产?

class A:
    def __init__(self,value):
        self.value=value
    def function(self,a):
        """function returns a+1 and caches the value for future calls."""
        cache=[]
        cache.append([a,a+1])
        return a+1;
a=A(12)
print a.function(12)
print a.function.cache

这给了我错误:

AttributeError: 'function' object has no attribute 'cache'

我知道可以为主类分配缓存,但我正在寻找一种可能的方法将其作为属性分配给方法对象。

1 个答案:

答案 0 :(得分:1)

class A:
    def __init__(self,value):
        self.value=value
        self.cache = {}
    def function(self,a):
        """function returns a+1 and caches the value for future calls."""

        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.cache.get(a,''):
            return self.cache[a]
        else:
            result = a + 1
            self.cache[a] = result
            return result

据我所知,没有办法将缓存作为方法的属性。 Python没有这样的功能。但我想也许这个解决方案可以满足您的需求。

修改

经过进一步研究,确实有一种方法可以在Python 3中实现这一点

class A:
    def __init__(self,value):
        self.value=value

    def function(self,a):
        """function returns a+1 and caches the value for future calls."""
        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.function.cache.get(a,''):
            return self.function.cache[a]
        else:
            result = a + 1
            self.function.cache[a] = result
            return result
    function.cache = {}


a=A(12)
print(a.function(12))
print(a.function.cache)

这是因为在Python 3中,实例方法只是函数。在Python 2中BTW确实可以向函数添加属性,但不能向实例方法添加属性。如果你需要使用Python 2,那么你应该研究一下solution to your problem involving decorators