5

我希望能够写入字节数组缓冲区并通过调用方法来清除它,所以我有一个如下所示的类:

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

1 回答 1

1

代替

    self = ""

    self[:] = ""

否则,您所做的就是重新绑定self引用。

同样,以下内容不会达到您的预期:

    self = message
于 2013-02-02T19:30:51.470 回答