7

I have a simple class that inherits from the NumPy n-dimensional array. I want to have two methods of the class that can change the array values of an instance of the class. One of the methods should set the array of the class instance to the values of a list data attribute of the class instance and the other of the methods should append some list values to the array of the class instance. I'm not sure how to accomplish this, but my attempt is as follows:

import numpy

class Variable(numpy.ndarray):

    def __new__(cls, name = "zappo"):
        self = numpy.asarray([]).view(cls)
        self._values            = [1, 2, 3] # list of values
        return(self)

    def updateNumPyArrayWithValues(self):
        self = numpy.asarray(self._values)

    def appendToNumPyArray(self):
        self = numpy.append(self, [4, 5, 6])

a = Variable()
print(a)
a.updateNumPyArrayWithValues()
print(a)

As a quick, preemptive question, would this class survive standard NumPy array operations such as the following?:

>>> v1 = np.array([23, 20, 13, 24, 25, 28, 26, 17, 18, 29])
>>> v1 = v1[v1 >= 20]

So, could I do similar things with my class and have all of its data attributes retained?

1
  • 1
    Writing self = something doesn't accomplish much in Python, except possibly in __new__ where you are returning it. In other methods, you want to change the content of self, e.g. by writing self[:] = somevalues. Commented Jan 12, 2015 at 20:22

1 Answer 1

15

You can do it like this:

class Variable(np.ndarray):

    def __new__(cls, a):
        obj = np.asarray(a).view(cls)
        return obj

    def updateNumPyArrayWithValues(self):
        self[1] = 1
        return self

>>> v = Variable([1,2,3])
>>> v
Variable([1, 2, 3])
>>> v.updateNumPyArrayWithValues()
Variable([1, 1, 3])
>>> v[v>1]
Variable([3])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help on this. How would I be able to create the class instance without defining the content of the NumPy array, as in my code, and then be able to update it with the data attribute list (of some arbitrary size)? In practice, what I'm going to be doing is using a method of the instance that loads a list of values and then saves them to the self NumPy array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.