numpy subclassing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jpecci
    New Member
    • Jul 2009
    • 3

    numpy subclassing

    I would like to ask you a quick question:
    I am facing the opposite problem described here:


    In short, I want to create a class Dummy(np.ndarra y) which returns a plain array whenever is sliced or viewed. I cannot figure out how.

    I would really appreciate you help, here is a chunk of code, what is commented was an attempt which didn’t work.
    Thanks a lot,
    Jacopo

    Code:
    import numpy as np 
    
    class Dummy(np.ndarray): 
    
        def __del__(self): 
            print "__del__" 
        def __new__(cls, array): 
            print "__new__" 
            obj=array.view(cls) 
            return obj 
        def __array_finalize__(self, obj): 
            print "__array_finalize__" 
            #self=self.view(np.ndarray) 
            #self=np.asarray(self) 
        def __repr__(self): 
            return "%s"%np.asarray(self) 
    
    p=Dummy(np.ones(5)) 
    print type(p)
    Last edited by bvdet; Jul 23 '09, 02:53 PM. Reason: add code tags and indentation
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I don't know much about Numpy. If I understand you correctly, you want a slice of an instance of your subclass to return a list or tuple. Try defining a __getslice__() method.
    Code:
    import numpy as np
    
    class N(np.ndarray):
        
        def __new__(cls, obj): 
            return obj.view(cls) 
    
        def __getslice__(self,i=None,j=None):
            return tuple(self.view()[i:j:])
    
    p = N(np.ones(9))
    print p
    print p[1:3]
    print p[:3]
    print p[3:]
    print p[1:8:3]
    Output:
    Code:
    >>> [ 1.  1.  1.  1.  1.  1.  1.  1.  1.]
    (1.0, 1.0)
    (1.0, 1.0, 1.0)
    (1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
    [ 1.  1.  1.]
    It does not work for a slice with a stride. The __getslice__() method has been deprecated since version 2.0.

    Comment

    • jpecci
      New Member
      • Jul 2009
      • 3

      #3
      thanks a lot. I think I will do something on these lines even if
      I was hoping in something which didnt involve getslice() since it has been deprecated.
      jacopo

      Comment

      Working...