自定义属性行为

时间:2015-11-17 11:56:49

标签: python python-2.7 python-decorators

我有一个成员必须映射到外部存储器的类。 当我读取它们的值时,我想从内存中读取它,当我设置它时,我想将它写入外部存储器。

我试图实现描述符协议,使这些字段的行为类似于属性:

class PagedField(object):

    def __init__(self, memory, page, offset, count, converter=bytearray):
        # memory is just a subclass of bytearray with some fancy methods
        self.memory = memory
        self.page = page
        self.offset = offset
        self.count = count

        # The value is automatically converted during get()
        self.converter = converter
        self._value = None

    def __get__(self, instance, cls):
        self._value = self.converter(self.memory.get(self.page, self.offset, self.count))
        return self._value

    def __set__(self, instance, value):
        if value is None:
            value = ''

        val = str(value)                # Everything is written to the memory as a string
        val = val[0:self.count]         # cut to the maximum allocated length
        while len(val) < self.count:    # fill with 0s
            val += chr(0)

        # Store and write to memory
        self._value = val
        self.memory.set(page_index=self.page, data=str(self._value), offset=self.offset)

但是,我必须遗漏一些东西。如果我尝试分配字段,则字段本身会覆盖该值。例如:

mem = bytearray(100)

class Foo:
    x = PagedField(mem, 0, 0, 10, str)

f = Foo()
f.x = "hello"
print type(f.x)

表明f.x现在是一个字符串。我做错了什么?

1 个答案:

答案 0 :(得分:2)

在Python 2中,您需要继承表单object以获得新样式的类。只有新式类支持描述符(和属性)。因此,您需要将class Foo:更改为class Foo(object):。在Python 3中,这不是必需的,因为删除了旧式类。