I’m trying to implement caching of value returned from database:
class Foo
...
def getTag(self):
value = self._Db.get(self._f[F_TAG])
setattr(self, 'tag', value)
return value
def _setTag(self, tag):
self._Db.set(self._f[F_TAG], tag)
tag = property(getTag)
...
x = Foo()
x._setTag("20")
print(x.tag)
x._setTag("40")
print(x.tag)
When I first time handle tag property, it must get value from DB and override class field tag with instance field for following use, but error occurs:
Traceback (most recent call last):
File "/home/altera/www/autoblog/core/dbObject.py", line 99, in <module>
print(x.tag)
File "/home/altera/www/autoblog/core/dbObject.py", line 78, in getTag
setattr(self, 'tag', value)
AttributeError: can't set attribute
Unfortunately it’s impossible to override a
@property. This is because the@propertyis attached to the class, not the instance.You can either make your
@propertygetter slightly more complex:Or create a descriptor which will do the caching for you: