Subclassing numarray's arrays

Colin J. Williams cjw at
Sun Aug 15 14:10:41 CEST 2004

Mizrandir wrote:
> First of all, thanks for helping.
>>Numarray wasn't designed with subclassing in mind, but there are
>>workarounds for most problems.
> On numarray's website there is a paper by the Numarray authors saying:
> "... The new approach allows arrays to be subclassed as well as ...",
> so I thought it should be something easy to do.
I don't remember that, but it is not as dificult as it looks.  Just try
out the code below, nothing could be simpler than the __init__ method

The __str__ and __repr__ are just tools which can be used with any subclass.
> Anyway, I hadn't read anything about numarraycore, is it explained
> anywhere. For example, I don't understand what the statement
> "self.__setstate__(arr.__getstate__())" does.
NumArray creates a number of attributes to provide information about the 
shape of an array, the data type of its elements and to point to the 
memory buffer containing the binary data etc.  The expression above just 
transfers the values from arr (which is an instance of NumArray) to
self (which is an instance of NewClass).
>>You might try something like:
>>import numarray.numarraycore as _num
>>class NewClass(_num.NumArray):
>>   def __init__(self, n, a):
>>     ''' n provides the length of each dimension,
>>         a is the constant value to be plugged.
>>       '''
>>     arr= _num.array(sequence= n * n * [a], shape= (n, n))
>>     self.__setstate__(arr.__getstate__())
>>   def __repr__(self):
>>     " Return printable representation of instance."
>>     className= self.__class__.__name__
>>     className= className.zfill(5).replace('0', ' ')
>>     arr= self.copy()
>>     arr.__class__= _num.NumArray
>>     rep= className + _num.NumArray.__repr__(arr)[5:]
>>     return rep
>>   def __str__(self):
>>     " Return a pretty printed string of the instance."
>>     stri= self.copy()
>>     stri.__class__= _num.NumArray
>>     return _num.NumArray.__str__(stri)
>>if __name__ == '__main__':
>>   a= NewClass(2, 2)
>>   print a
>>   b= NewClass(3, 4)
>>   print `b`
> miz.
Please let me know if I can provide any further information.  numarray
is a good tool, but there is a  small hurdle if one wishes to subclass.

Colin W.

More information about the Python-list mailing list