Search code examples
pythonconstructornew-operator

How to subclass array.array and have its derived constructor take no parameters in python?


I want to encapsulate a python array to fix it's typecode and hide it from the user. I thought I could use derivation to accomplish this, but I am not able to construct my Type because it is missing a 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 the constructor instead.

EDIT: Sven Marnach suggested to add self which pointed me to add the missing cls parmeter in the __new__ version which works.

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

myBuffer = MyBinaryBuffer()

Solution

  • You need to use the __new__ method, since __init__ gets it already constructed. But You don't use super there.

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