假设我有一个类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}$我知道可以将缓存分配给主类,但我正在寻找一种可能的方法,将其作为属性分配给方法对象。在
据我所知,无法将缓存作为方法的属性。Python没有这样的功能。但我认为这个解决方案也许能满足你的需要。在
编辑
经过进一步的研究,在python3中确实有一种方法可以做到这一点
^{pr2}$这是因为在Python中,3个实例方法只是函数。顺便说一句,在python2中,确实可以向函数添加属性,但不能向实例方法添加属性。如果您需要使用python2,那么您应该研究一下solution to your problem involving decorators。在
相关问题 更多 >
编程相关推荐