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>

<blockquote>
  <blockquote>
    <h1>I'M SORRY FOR THE DARK MAGIC</h1>
  </blockquote>
</blockquote>

<p>Using <a href="http://clarete.li/forbiddenfruit/" rel="nofollow">Forbiddenfruit</a> and python python's builtin <code>new</code> method I was able to do this:</p>

<pre><code>from forbiddenfruit import curse


class MyThing(int):
    def __new__(cls, *args, **kwargs):
        magic_slice = slice(args[0], args[1])
        curse(slice, 'otherstuff', args[2])  

        return magic_slice

thing = MyThing(1, 3, 'thing')
print 'hello world'[thing]
print thing.otherstuff
</code></pre>

<p>output:</p>

<pre><code>&gt;&gt;&gt; el
&gt;&gt;&gt; thing
</code></pre>

<p><em><strong>I wrote it as a challenge just because everybody said it is impossible, I would never use it on production code IT HAS SO MANY SIDE EFFECTS, you should think again on your structure and needs</strong></em></p>

python slice