How does subclass array.array and its derived constructor not accept parameters in python?

I want to encapsulate a python array in order to fix its typecode and hide it from the user. I thought I could use the output to accomplish this, but I cannot build my type because it lacks the required parameter:

class MyBinaryBuffer(array.array):
    def __init__(self):
        array.array.__init__(self, 'B') #this is the fixed 'B' typecode parameter for 
                                  #array.array() constructor

myBuffer = MyBinaryBuffer()

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: array() takes at least 1 argument (0 given)

How could I implement this in a natural way?

After some research, I see that I should use a constructor instead.

EDIT: Sven Marnach suggested adding himself by pointing me to add the missing cls separator in the __ new __ version , which works .. p>

class MyBinaryBuffer(array.array):
    def __new__(cls):
        return super(MyBinaryBuffer, cls).__new__(cls, 'B')

myBuffer = MyBinaryBuffer()
+4
source share
3 answers

__new__, __init__ . super .

class OctetString(array):
    def __new__(cls):
        return array.__new__(cls, 'c')
+6

, new init:

:

class Point(array.array):
    '''
    an array.array with 3 coordinates [x,y,z]
    '''

    def __new__(cls, clist, parent=None, index=-1):
        while len(clist)<3: clist.append(0.0)
        return super(Point, cls).__new__(cls,'f', clist[0:3])


    def __init__(self, cList=[], parent=None, index=-1):
        self._parent = parent  # private
        self.index   = index   # public

    @property
    def parent(self):
        return self._parent

p = Point([1,2], parent='anyObject', index=5)
print(p, p.parent, p.index) 
0

Here is a method tested in both python2.x and python3.x:

from array import array


class MyBinaryBuffer(array):
    def __new__(cls, *args, **kwargs):
        return super(MyBinaryBuffer, cls).__new__(cls, 'B', *args, **kwargs)


b1 = MyBinaryBuffer([1, 2, 3])
b2 = MyBinaryBuffer()
print(b1, b2)

or if you want to avoid using super:

class MyBinaryBuffer(array):
    def __new__(cls, *args, **kwargs):
        return array.__new__(cls, 'B', *args, **kwargs)

In this particular case, you can fully emulate the behavior array.array, other existing answers do not guarantee this.

0
source

Source: https://habr.com/ru/post/1789360/


All Articles