Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting and extending Python bytearray

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?
like image 595
Peter Avatar asked Nov 12 '22 12:11

Peter


1 Answers

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
like image 93
NPE Avatar answered Nov 15 '22 07:11

NPE