通过扩展Python str来创建缓冲类

时间:2013-02-02 09:10:09

标签: python

我想这可以通过代码和评论来解释:

import struct

class binary_buffer(str):
    def __init__(self, msg=""):
        self = msg
    def write_ubyte(self, ubyte):
        self += struct.pack("=B", ubyte)
        return len(self)

Output
>> bb = binary_buffer()
>> bb # Buffer starts out empty, as it should
''
>> bb.write_ubyte(200)
1   # We can see that we've successfully written one byte to the buffer
>> bb
''  # Huh? We just wrote something, but where has it gone?

1 个答案:

答案 0 :(得分:4)

str是不可变的。因此,

self += struct.pack("=B", ubyte)

评估为

self = self + struct.pack("=B", ubyte)

这为名称self指定了一个新值,但self只是一个与其他名称一样的名称。一旦方法退出,名称(和相关对象)就会被遗忘。

您需要bytearray

>>> bb = bytearray()
>>> bb.append(200)
>>> bb
bytearray(b'\xc8')