how do I write a scliceable class?

Alf P. Steinbach alfps at
Sat Feb 13 14:20:15 CET 2010

* Ernest Adrogué:
> 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.

I'd go for it anyway, because the programmer who subclasses needs to understand 
the base class. And if, say, that class has a custom _init method, and it's 
documented that that what's a subclass should override, then, OK. No problem.

> So what is there to do? Any suggestion?

An alternative can be to simply check for argument value None in the 
constructor, and if so, don't do anything.

Cheers & hth.,

- Alf

More information about the Python-list mailing list