【发布时间】: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