Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以面向对象的方式将缓存分配给方法?_Python_Memoization - Fatal编程技术网

Python 如何以面向对象的方式将缓存分配给方法?

Python 如何以面向对象的方式将缓存分配给方法?,python,memoization,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=[]

假设我有一个类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'
我知道可以将缓存分配给主类,但我正在寻找一种可能的方法,将其作为属性分配给方法对象

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没有这样的特性。但我认为这个解决方案也许能满足你的需要

编辑

经过进一步研究,在Python3中确实有一种方法可以做到这一点

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)
这是因为在Python3中,实例方法只是函数。顺便说一句,在Python2中,确实可以向函数添加属性,但不能向实例方法添加属性。如果您需要使用Python2,那么有一个问题需要研究

据我所知,没有办法将缓存作为方法的属性。Python没有这样的特性。但我认为这个解决方案也许能满足你的需要

编辑

经过进一步研究,在Python3中确实有一种方法可以做到这一点

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)

这是因为在Python3中,实例方法只是函数。顺便说一句,在Python2中,确实可以向函数添加属性,但不能向实例方法添加属性。如果您需要使用Python2,那么有一个问题需要研究

Kodus to van Rossum:D那么如果我有三个函数,那么我基本上就完蛋了,因为在这种情况下,我必须手动按它们的名称为函数分配缓存@纳吉:尽管你已经接受了这个答案,但更好的解决办法是接受msw的建议,使用标准的记忆技术。从Python3.2开始,它再简单不过了:只需使用
@functools.lru\u缓存
decorator。但即使在Python2中,也不难做到这一点。此外,缓存不需要是属性。您不应该需要从正在缓存的函数外部访问缓存。记忆函数应该能处理所有这些。Kodus to van Rossum:D那么如果我有三个函数,那么我基本上就完蛋了,因为在这种情况下,我必须手动根据它们的名称为函数分配缓存@纳吉:尽管你已经接受了这个答案,但更好的解决办法是接受msw的建议,使用标准的记忆技术。从Python3.2开始,它再简单不过了:只需使用
@functools.lru\u缓存
decorator。但即使在Python2中,也不难做到这一点。此外,缓存不需要是属性。您不应该需要从正在缓存的函数外部访问缓存。memorized函数应该处理所有这些。为什么您希望一个方法具有任意属性,为什么您希望对将来的代码读者(可能是您)这样做?@msw因为这个方法可能会进行非常复杂的计算,我可能会用相同的参数多次调用它。有了这个缓存思想,我可以立即返回它的值,而无需重新计算它。我认为,在企业应用程序中,您经常需要这样的缓存机制。它是被调用的,Python中有一种定义良好的方法来实现它。为什么您希望一个方法具有任意属性,为什么您希望对将来的代码读者(您可能是谁)这样做?@msw,因为此方法可能会进行非常复杂的计算,我可能会使用相同的参数多次调用它。有了这个缓存思想,我可以立即返回它的值,而无需重新计算它。我认为在企业应用程序中,您经常需要这样的缓存机制。它被称为,在Python中有一种定义良好的方法来实现。