Connecting Tech Pros Worldwide Forums | Help | Site Map

numpy subclassing

Newbie
 
Join Date: Jul 2009
Posts: 3
#1: Jul 23 '09
I would like to ask you a quick question:
I am facing the opposite problem described here:
http://docs.scipy.org/doc/numpy/user...bclassing.html

In short, I want to create a class Dummy(np.ndarray) 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

Expand|Select|Wrap|Line Numbers
  1. import numpy as np 
  2.  
  3. class Dummy(np.ndarray): 
  4.  
  5.     def __del__(self): 
  6.         print "__del__" 
  7.     def __new__(cls, array): 
  8.         print "__new__" 
  9.         obj=array.view(cls) 
  10.         return obj 
  11.     def __array_finalize__(self, obj): 
  12.         print "__array_finalize__" 
  13.         #self=self.view(np.ndarray) 
  14.         #self=np.asarray(self) 
  15.     def __repr__(self): 
  16.         return "%s"%np.asarray(self) 
  17.  
  18. p=Dummy(np.ones(5)) 
  19. print type(p)

bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,566
#2: Jul 25 '09

re: numpy subclassing


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.
Expand|Select|Wrap|Line Numbers
  1. import numpy as np
  2.  
  3. class N(np.ndarray):
  4.  
  5.     def __new__(cls, obj): 
  6.         return obj.view(cls) 
  7.  
  8.     def __getslice__(self,i=None,j=None):
  9.         return tuple(self.view()[i:j:])
  10.  
  11. p = N(np.ones(9))
  12. print p
  13. print p[1:3]
  14. print p[:3]
  15. print p[3:]
  16. print p[1:8:3]
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> [ 1.  1.  1.  1.  1.  1.  1.  1.  1.]
  2. (1.0, 1.0)
  3. (1.0, 1.0, 1.0)
  4. (1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
  5. [ 1.  1.  1.]
It does not work for a slice with a stride. The __getslice__() method has been deprecated since version 2.0.
Newbie
 
Join Date: Jul 2009
Posts: 3
#3: Jul 26 '09

re: numpy subclassing


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
Reply