gpt4 book ai didi

python - 如何以 OOP 方式将缓存分配给方法?

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:34 25 4
gpt4 key购买 nike

假设我有类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没有这样的功能。但我想也许这个解决方案会满足您的需求。

编辑

经过进一步研究,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 中确实可以向函数添加属性,但不能向实例方法添加属性。如果您需要使用Python 2,那么有solution to your problem involving decorators你应该调查一下。

关于python - 如何以 OOP 方式将缓存分配给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17345669/

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