Ensuring __init__ is only called once when class instance is created by constructor or __new__
<p>I'm trying to understand how new instances of a Python class should be created when the creation process can either be via the constructor or via the <code>__new__</code> method. In particular, I notice that when using the constructor, the <code>__init__</code> method will be automatically called after <code>__new__</code>, while when invoking <code>__new__</code> directly the <code>__init__</code> class will not automatically be called. I can force <code>__init__</code> to be called when <code>__new__</code> is explicitly called by embedding a call to <code>__init__</code> within <code>__new__</code>, but then <code>__init__</code> will end up getting called twice when the class is created via the constructor.</p>

<p>For example, consider the following toy class, which stores one internal property, namely a <code>list</code> object called <code>data</code>: it is useful to think of this as the start of a vector class.</p>

<pre><code>class MyClass(object):
    def __new__(cls, *args, **kwargs):
        obj = object.__new__(cls, *args, **kwargs)
        obj.__init__(*args, **kwargs)
        return obj

    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        return self.__new__(type(self), self.data[index])

    def __repr__(self):
        return repr(self.data)
</code></pre>

<p>A new instance of the class can be created either using the constructor (not actually sure if that is the right terminology in Python), something like</p>

<p><code>x = MyClass(range(10))</code></p>

<p>or via slicing, which you can see invokes a call to <code>__new__</code> in the <code>__getitem__</code> method.</p>

<p><code>x2 = x[0:2]</code></p>

<p>In the first instance, <code>__init__</code> will be called twice (both via the explicit call within <code>__new__</code> and then again automatically), and once in the second instance. Obviously I would only like <code>__init__</code> to be invoked once in any case. Is there a standard way to do this in Python?</p>

<p>Note that in my example I could get rid of the <code>__new__</code> method and redefine <code>__getitem__</code> as</p>

<pre><code>def __getitem__(self, index):
    return MyClass(self.data[index])
</code></pre>

<p>but then this would cause a problem if I later want to inherit from <code>MyClass</code>, because if I make a call like <code>child_instance[0:2]</code> I will get back an instance of <code>MyClass</code>, not the child class.</p>
