how do I write a scliceable class?

Peter Otten __peter__ at web.de
Sat Feb 13 09:16:31 EST 2010


Ernest Adrogué wrote:

> I'm designing a container class that supports slicing.
> The problem is that I don't really know how to do it.
> 
> class MyClass(object):
>         def __init__(self, input_data):
>                 self._data = transform_input(input_data)
>         def __getitem__(self, key):
>                 if isinstance(key, slice):
>                         # return a slice of self
>                         pass
>                 else:
>                         # return a scalar value
>                         return self._data[key]
> 
> The question is how to return a slice of self.
> First I need to create a new instance... but how? I can't
> use MyClass(self._data[key]) because the __init__ method
> expects a different kind of input data.
> 
> Another option is
> 
> out = MyClass.__new__(MyClass)
> out._data = self._data[key]
> return out
> 
> But then the __init__ method is not called, which is
> undesirable because subclasses of this class might need
> to set some custom settings in their __init__ method.
> 
> So what is there to do? Any suggestion?

Either 

(1) make transform_input() idempotent, i. e. ensure that

transform_input(transform_input(data)) == transform_input(data)

and construct the slice with MyClass(self._data[key])

or 

(2) require it to be invertible with

inverse_transform_input(transform_input(data)) == data

and make the slice with MyClass(inverse_transform_input(self._data[key]))

Just stating the obvious...

Peter



More information about the Python-list mailing list