[Tutor] Creating a subclass of NumArray
ligon@are.berkeley.edu
ligon at are.berkeley.edu
Thu Aug 18 00:44:00 CEST 2005
I'd like to be able to instantiate and work with objects
which possess the properties of matrices, but which also
carry some additional information.
Numarray provides a NumArray object which can be treated as
a matrix. One way to instantiate these objects is by a call
to a function array, like
>>> from numarray import *
>>> x=array([[1,2],[3,4]])
>>> print x
[[1 2]
[3 4]]
>>> print x.__class__
<class 'numarray.numarraycore.NumArray'>
What I'd like to do is create a subclass of
NumArray; something like:
>>> class MyArray(numarraycore.NumArray):
... def __init__(self,x):
... numarraycore.NumArray.__init__(self,x)
... self.myfield={}
However, the function array which I used above to instantiate
an NumArray object isn't at all the same as
numarraycore.NumArray.__init__(). The latter takes a much
more complicated set of arguments, so that:
>>> y=MyArray(x)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __init__
ValueError: invalid shape tuple
I'd *like* to use the simpler instantiation provided by array();
something like:
>>> class MyArray(numarraycore.NumArray):
... def __init__(self,x):
... self=array(x)
... self.myfield={}
...
But this doesn't work:
>>> y=MyArray(x)
>>> print y
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/site-packages/numarray/numarraycore.py", line 711, in __str__
return array_str(self)
File "/usr/lib/python2.3/site-packages/numarray/numarraycore.py", line 1357, in array_str
return arrayprint.array2string(
File "/usr/lib/python2.3/site-packages/numarray/arrayprint.py", line 178, in array2string
x = a[()]
libnumarray.error: can't get buffer size
Presumably y hasn't really properly inherited all the attributes of a
NumArray. What's the right way to solve this problem? For bonus
points, is it possible to solve it without delving too deeply into
the guts of numarray?
Thanks,
-Ethan
--
Ethan Ligon, Assoc. Professor ligon at are.berkeley.edu
Dept. of Agricultural & Resource Economics
University of California http://are.berkeley.edu/~ligon
Berkeley, CA 94720-3310 (510)643-5411
More information about the Tutor
mailing list