【问题标题】:Custom property behaviour自定义属性行为
【发布时间】:2016-02-18 18:53:09
【问题描述】:

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

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

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 现在是一个字符串。我做错了什么?

【问题讨论】:

  • class Foo 不继承自 object
  • 你是对的,解决了它!你能解释一下为什么吗?我不明白。

标签: python python-2.7 python-decorators


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2015-08-09
    相关资源
    最近更新 更多