By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,957 Members | 2,017 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,957 IT Pros & Developers. It's quick & easy.

numpy subclassing

P: 3
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)
Jul 23 '09 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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.
Jul 25 '09 #2

P: 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
Jul 26 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.