Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.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/8/python-3.x/19.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 @property是否可以像缓存字典一样工作?_Python_Python 3.x_Dictionary_Caching_Properties - Fatal编程技术网

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']
,实现访问,基于我对PythonMake
bar
的有限理解,这是一个对象,它使用适当的缓存实现
\uuuu getitem\uuuu
,然后将其作为
foo
@Athenawise>的属性,为什么不使用一个方法呢?@ekhumaro试图通过保持不变来避免修改使用未缓存字典的现有代码使用缓存字典时的语法。我认为Samwise的建议有效。