继承和扩展 Python bytearray

Pet*_*ter 5 python inheritance 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 = ""
Run Code Online (Sandbox Code Playgroud)

但是,调用 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?
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 1

代替

    self = ""
Run Code Online (Sandbox Code Playgroud)

    self[:] = ""
Run Code Online (Sandbox Code Playgroud)

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

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

    self = message
Run Code Online (Sandbox Code Playgroud)