[Numpy-discussion] subclassing
Keith Goodman
kwgoodman@gmail....
Tue Sep 29 13:19:22 CDT 2009
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?
More information about the NumPy-Discussion
mailing list