[Numpy-discussion] subclassing

Keith Goodman kwgoodman at gmail.com
Tue Sep 29 14:56:47 EDT 2009


On Tue, Sep 29, 2009 at 11:25 AM, Robert Kern <robert.kern at gmail.com> wrote:
> On Tue, Sep 29, 2009 at 13:19, Keith Goodman <kwgoodman at 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.'

Thank you!

I wonder if I'll ever come across a problem that you cannot solve, Robert.



More information about the NumPy-Discussion mailing list