0

我正在尝试实现从数据库返回的值的缓存:

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)

当我第一次处理标签属性时,它必须从数据库中获取值并用实例字段覆盖字段标签以供后续使用,但出现错误:

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
4

2 回答 2

2

不幸的是,无法覆盖@property. 这是因为@property附加到类,而不是实例。

您可以使您的@property吸气剂稍微复杂一些:

@property
def tag(self):
    try:
        return self._db_values["tag"]
    except KeyError:
        pass
   val = self._db.get("tag")
   self._db_values["tag"] = val
   return val

或者创建一个描述符来为你做缓存:

Undefined = object()

class DBValue(object):
    def __init__(self, column_name):
        self.column_name = column_name
        self.value = Undefined

    def __get__(self, instance, owner):
        if self.value is Undefined:
            self.value = instance._db.get(self.column_name)
        return self.value

class Foo(object):
    tag = DBValue("tag")
于 2012-09-19T21:34:08.617 回答
0

x.tag是一个属性并且没有设置器,所以当你尝试设置它时,你会因为明显的原因得到一个错误。因此,将实际值存储在“私有”字段中,例如x._tag并为其编写一个 getter 和 setter。

class Foo(object):

    _tag = None

    @property
    def tag(self):
        if self._tag is None:
            self._tag = self._Db.get(self._f[F_TAG])
        return self._tag

    @tag.setter
    def tag(self, tag):
        self._tag = tag
        self._Db.set(self._f[F_TAG], tag)

x = Foo()
print x.tag    # gets the value from the database (if necessary) or f._tag
x.tag = "bar"  # sets the value in the database and caches it in f._tag
于 2012-09-19T21:38:11.393 回答