我希望能够写入一个bytearray缓冲区并通过调用方法来清除它,所以我有一个看起来像这样的类:
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?
答案 0 :(得分:1)
替换
self = ""
与
self[:] = ""
否则你所做的只是重新绑定self
引用。
同样,以下内容并不符合您的期望:
self = message