Slice inconsistency?
Roberto A. F. De Almeida
roberto at dealmeida.net
Fri Sep 26 16:45:54 EDT 2003
I found that when using negative indices, the slice object passed to
__getitem__ depends on the number of slices. An example to clarify:
class a:
def __getitem__(self, index):
return index
>>> b = a()
>>> print b[:-1]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: a instance has no attribute '__len__'
But if I pass a "multiple" slice:
>>> print b[:-1,:-1]
(slice(None, -1, None), slice(None, -1, None))
If we add the following __len__ to class a:
def __len__(self):
return 42
Then the "single" slice works based on __len__:
>>> print b[:-1]
slice(0, 41, None)
But not for the "multiple" slice:
>>> print b[:-1,:-1]
(slice(None, -1, None), slice(None, -1, None))
I am having these problems because I want to slice a multi-dimensional
object. When slicing the object, __getitem__ returns a Numeric array
of the desired size:
>>> print data
<opendap.client.dataset instance at 0x406304ec>
>>> print data.variables['u'].shape
(16, 17, 21)
>>> u = data.variables['u'][:,:,:]
>>> print type(u)
<type 'array'>
>>> print u.shape
(16, 17, 21)
>>> u[0,0,0]
-1728
Is there something wrong in using slices like this in objects? A
better way?
More information about the Python-list
mailing list