I am trying to let a class Foo have a @property named bars that behaves like a Python Dictionary where we can access the values in bars using keys and [ ]:
foo = Foo()
foo.bars['hello']
The reason for using the @property decorator is to allow caching of the key values on first access:
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]
Unfortunately, the above code leads to the error:
TypeError: bars() missing 1 required positional argument: 'key'
Is it possible to accomplish this using @property?