Python @property是否可以像缓存字典一样工作?
我试图让一个类Python @property是否可以像缓存字典一样工作?,python,python-3.x,dictionary,caching,properties,Python,Python 3.x,Dictionary,Caching,Properties,我试图让一个类Foo拥有一个名为bar的@属性,它的行为类似于一个Python字典,我们可以使用键和[]访问bar中的值: foo = Foo() foo.bars['hello'] 使用@property装饰器的原因是允许在首次访问时缓存键值: class Foo(): def __init__(self): self._bars = {} @property def bars(self, key): # <--- looks like
Foo
拥有一个名为bar
的@属性,它的行为类似于一个Python字典,我们可以使用键和[
]访问bar
中的值:
foo = Foo()
foo.bars['hello']
使用@property
装饰器的原因是允许在首次访问时缓存键值:
class Foo():
def __init__(self):
self._bars = {}
@property
def bars(self, key): # <--- looks like this function signature doesnt work
if key not in self._bars.keys():
self._bars[key] = hash(key) # cache computation results on first access
return self._bars[key]
是否可以使用@property
完成此操作?这是否回答了您的问题@同样,链接问题中的解决方案可以帮助我们使用foo['hello']
,而不是foo.bar['hello']
,实现访问,基于我对PythonMakebar
的有限理解,这是一个对象,它使用适当的缓存实现\uuuu getitem\uuuu
,然后将其作为foo
@Athenawise>的属性,为什么不使用一个方法呢?@ekhumaro试图通过保持不变来避免修改使用未缓存字典的现有代码使用缓存字典时的语法。我认为Samwise的建议有效。