Mizrandir wrote:
I'd like to subclass numarray's array. I'd like to add some methods
and override others like __init__. I don't know how to do this and
haven't found help searching the manual or the web, can someone help?
For example imagine I just want to do something as simple as making a
subclass "NewClass" with the __init__ method overridden so that the
behaviour would be:
a = NewClass(2)
print a
[[2 2]
[2 2]]
How could that be done?
Thanks in advance, miz.
Miz,
Numarray wasn't designed with subclassing in mind, but there are
workarounds for most problems.
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`
I hope that this helps.
Colin W.