How to extend Numpy array class with append() function?

Viewed 239

How can I achieve:

>>> foo = np.array([1,2,3])
array([1,2,3])
>>> foo.append(4)
array([1,2,3,4])

Instead of numpy's:

np.append(foo, 4)

I've tried stuff along the lines of:

import numpy as np
class myarrayclass(np.array):
    def append(self, value):
        self.object = np.append(self.object, value)

Also, is it possible to overwrite the numpy class instead of creating my own? I don't need this to work, just wondering if it is possible, thanks in advance!

1 Answers

I am not sure if this is the best way, but here is one approach.

import numpy as np

class myarrayclass(object):
    def __init__(self, in_array):
        self.array = in_array
        
    def append(self, val):
        self.array = np.append(self.array, val)
      
    def show(self):
        return self.array
        
        
foo = np.array([1,2,3])


myarray = myarrayclass(foo)
myarray.append(5)

myarray.show()
#Out[7]: array([1, 2, 3, 5])

When you make an object, you need to initialize it with def __init__(self, in_array). Here I have included a simple append and show method. I included the show method to demonstrate that the append worked.

Related