Make an object that behaves like a slice
<p>How can we make a class represent itself as a slice when appropriate?</p>

<p>This didn't work:</p>

<pre><code>class MyThing(object):
    def __init__(self, start, stop, otherstuff):
        self.start = start
        self.stop = stop
        self.otherstuff = otherstuff
    def __index__(self):
        return slice(self.start, self.stop)
</code></pre>

<p>Expected output:</p>

<pre><code>&gt;&gt;&gt; thing = MyThing(1, 3, 'potato')
&gt;&gt;&gt; 'hello world'[thing]
'el'
</code></pre>

<p>Actual output:</p>

<pre><code>TypeError: __index__ returned non-(int,long) (type slice)
</code></pre>

<p>Inheriting from <code>slice</code> doesn't work either.  </p>

<p>A slice can't be in your return type as the method just doesn't support this. You can read more about the <code>__index__</code> <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">special method here</a>.
I could only come up with a workaround that directly calls the function in your class:</p>

<pre><code>class MyThing(object):
        def __init__(self, start, stop, otherstuff):
            self.start = start
            self.stop = stop
            self.otherstuff = otherstuff  

        def __index__(self):
            return slice(self.start, self.stop)

    thing = MyThing(1, 3, 'potato')
    print 'Hello World'[thing.__index__()]
</code></pre>

<p>This will return <code>el</code>.</p>

python slice