1

我想这最好用代码和注释来解释:

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?
4

1 回答 1

4

strs 是不可变的。所以,

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

被评估为

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

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

你想要一个bytearray

>>> bb = bytearray()
>>> bb.append(200)
>>> bb
bytearray(b'\xc8')
于 2013-02-02T09:13:02.710 回答