how do I write a scliceable class?

Robert Kern robert.kern at gmail.com
Sat Feb 13 11:33:53 EST 2010


On 2010-02-13 06:51 , Ernest Adrogué wrote:
> Hello everybody,
>
> 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?

I highly recommend making __init__() constructors do as little computation as 
possible. You can add other constructors using @classmethod that do convenient 
transformations.

-- 
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 Python-list mailing list