views:

49

answers:

2

I'd like to make a class extending the numpy array base type,

class LemmaMatrix(numpy.ndarray):
    @classmethod
    def init_from_corpus(cls, ...): cls(numpy.empty(...))

But apparently, it will not allow multi-dimensional array types. Is there a way around this? Thanks in advance!

ndarray(empty([3, 3]))
TypeError: only length-1 arrays can be converted to Python scalars
A: 

Inheritance of types written in C is seldom useful. Are you sure you do not want to define a class that stores a numpy array as an attribute or to define functions that take numpy arrays as arguments? In what way are you extending ndarray?

Mike Graham
for passing them around in the usual dynamic-type code style :) When one has something that's almost exactly like a matrix type, but has a few functions / extra data attached, this kind of wrapping is nice. At a high level, it's a matrix with some semantics.
gatoatigrado
@gatoatigrado, Something doing something similar to something else isn't a great reason to use subclassing. Composition often proves superior.
Mike Graham
+1  A: 
import numpy as np
class LemmaMatrix(np.ndarray):
    def __new__(subtype,data,dtype=None):
        subarr=np.empty(data,dtype=dtype)
        return subarr

lm=LemmaMatrix([3,3])
print(lm)
# [[  3.15913337e-260   4.94951870e+173   4.88364603e-309]
#  [  1.63321355e-301   4.80218258e-309   2.05227026e-287]
#  [  2.10277051e-309   2.07088188e+289   7.29366696e-304]]

You may also want read this guide for more information on how to subclass ndarray.

unutbu
That looks great; the numpy.empty.view(LemmaMatrix) also seems good. Thanks! :)
gatoatigrado
One minor thing -- why not $size instead of $data? It is the dimensions, not the values, clearly?
gatoatigrado
@gatoatigrado: By all means, you could use something like `np.array(data).size`. I was guessing -- perhaps incorrectly -- what you wanted.
unutbu