I want to be able to write to a bytearray buffer and to clear it by calling a method, so I have a class that looks like this:
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 = ""
However, calling clear() does not seem to do anything at all. A sample output would look like this:
>>> 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?
Replace
self = ""
with
self[:] = ""
Otherwise all you're doing is rebinding the self
reference.
Similarly, the following doesn't do what you expect:
self = message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With