我希望能够写入一个bytearray缓冲区并通过调用一个方法来清除它,所以我有一个如下所示的类: import structclass binary_buffer(bytearray): def __init__(self, message=""): self = message def write_ubyte(self, u
import struct class binary_buffer(bytearray): def __init__(self, message=""): self = message def write_ubyte(self, ubyte): self += struct.pack("=B", ubyte) return len(self) def clear(self): self = ""
但是,调用clear()似乎根本不做任何事情.示例输出如下所示:
>>> bb = binary_buffer('') >>> bb bytearray(b'') # As expected, the bytearray is empty >>> bb.write_ubyte(255) 1 # Great, we just wrote a unsigned byte! >>> bb bytearray(b'\xff') # Looking good. We have our unsigned byte in the bytearray. >>> bb.clear() # Lets start a new life! >>> bb bytearray(b'\xff') # Um... I though I just cleared out the trash?更换
self = ""
同
self[:] = ""
否则你所做的就是重新引导自引用.
同样,以下内容不符合您的预期:
self = message