我有一个类,其成员必须映射到外部存储器。 当我读取它们的值时,我想从内存中读取它,当我设置它时,我想将它写入外部存储器。
我已尝试实现描述符协议(protocol)以使这些字段的行为类似于属性:
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 现在是一个字符串。我做错了什么?
请您参考如下方法:
在 Python 2 中,你需要继承 object 的形式来获得一个新风格的类。只有新式类支持描述符(和属性)。因此,您需要将 class Foo: 更改为 class Foo(object):。在 Python 3 中,这不是必需的,因为旧式类已被删除。
