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

2024-05-03 02:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个类A,这个类有一个名为函数的方法。我可以将缓存作为属性分配给这个方法吗?在某种意义上我可以称之为财产?在

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

这给了我一个错误:

^{2}$

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


Tags: and方法函数selfcache属性initvalue
1条回答
网友
1楼 · 发布于 2024-05-03 02:31:16
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中确实有一种方法可以做到这一点

^{pr2}$

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

相关问题 更多 >