[Numpy-discussion] subclassing
Robert Kern
robert.kern@gmail....
Tue Sep 29 13:25:06 CDT 2009
On Tue, Sep 29, 2009 at 13:19, Keith Goodman <kwgoodman@gmail.com> wrote:
> I ran across a problem while using numpy. But the problem is more of
> python problem. I hope I am not too far off topic.
>
> I have a class and a subclass:
>
> class myclass:
>
> def __init__(self, x):
> self.x = x
>
> def __getitem__(self, index):
> if type(index) is slice:
> x = self.x[index]
> return myclass(x)
> else:
> raise IndexError, 'Only slicing is allowed in this example.'
>
> def calc(self):
> print 'myclass'
>
> def __repr__(self):
> return self.x.__repr__()
>
> class mysubclass(myclass):
>
> def calc(self):
> print 'mySUBclass'
>
>
> I can make an instance of mysubclass:
>
>>> sub = mysubclass(np.array([1,2,3]))
>>> sub
> array([1, 2, 3])
>>> sub.calc()
> mySUBclass
>
> The problem occurs when I slice:
>
>>> sub_slice = sub[1:]
>>> sub_slice.calc()
> myclass # <--- Oops. I'd like this to be mySUBclass
>
> Slicing causes sub to change from mysubclass to myclass. It does so
> because __getitem__ returns myclass(x). I could make a __setitem__
> method in mysubclass that returns mysubclass(x), but I have many such
> methods with the same problem (not shown in the code above). Is there
> another solution?
def __getitem__(self, index):
if type(index) is slice:
x = self.x[index]
return type(self)(x) # <----------
else:
raise IndexError, 'Only slicing is allowed in this example.'
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion
mailing list