[Numpy-discussion] subclassing ndarray

Steve Schmerler elcorto@gmx....
Fri Dec 5 09:10:41 CST 2008


Hi all

I'm subclassing ndarray following [1] and I'd like to know if i'm doing
it right. My goals are

- ndarray subclass MyArray with additional methods
- replacement for np.array, np.asarray on module level returning MyArray
  instances
- expose new methods as functions on module level
    
    import numpy as np

    class MyArray(np.ndarray):                                                    
        def __new__(cls, arr, **kwargs):                                   
            return np.asarray(arr, **kwargs).view(dtype=arr.dtype, type=cls)
        
        # define new methods here ...                                             
        def print_shape(self):                                                    
            print self.shape                                                      
                                                                                  
    # replace np.array()                                                          
    def array(*args, **kwargs):                                                   
        return MyArray(np.array(*args, **kwargs))                                 
                                                                                  
    # replace np.asarray()
    def asarray(*args, **kwargs):                                                 
        return MyArray(*args, **kwargs)                                           
                                                                                  
    # expose array method as function                                             
    def ps(a):                                                                    
        asarray(a).print_shape()     

Would that work?

PS: I found a little error in [1]:

In section "__new__ and __init__", the class def should read

    class C(object):
        def __new__(cls, *args):
+           print 'cls is:", cls
            print 'Args in __new__:', args
            return object.__new__(cls, *args)
        def __init__(self, *args):
+           print 'self is:", self
            print 'Args in __init__:', args


[1] http://docs.scipy.org/doc/numpy/user/basics.subclassing.html

best,
steve


More information about the Numpy-discussion mailing list