Python: how make class, inherited from list, with access to first element?
<p>In Python I would like to make class <em>MyList</em> and inherit from <em>list</em>. Besides I would like to make attribute <em>first</em>, which is equal to first element of list.
For example, for such code </p>

<pre><code>l = MyList([0, 1, 2])
print (l.first)
l.first = 3
print (l)
</code></pre>

<p>I would like to see</p>

<pre><code>0
[3, 1, 2]
</code></pre>

<p>I write</p>

<pre><code>class MyList(list):
    def __init__(self, input_list):
        self.first = input_list[0]

my_list = MyList([0, 1, 2])
print (my_list)
print (my_list.first)
</code></pre>

<p>and get</p>

<pre><code>[]
0
</code></pre>

<p>Why my_list is empty?</p>

<p>You're not calling list's <code>__init__</code> in your <code>__init__</code>.</p>

<pre><code>class MyList(list):
    def __init__(self, input_list):
        super(MyList, self).__init__(input_list)
        self.first = input_list[0]
</code></pre>

<p>Also, rather than affecting first at init, you should use a <a href="https://docs.python.org/2.7/library/functions.html#property" rel="nofollow">property</a> so as to return the first value even when the values of the list have been changed after initialization.</p>

<pre><code>class MyList(list):
    def __init__(self, input_list):
        super(MyList, self).__init__(input_list)

    @property
    def first(self):
        #Â TODO: catch empty list exception
        return self[0]
</code></pre>

<p>in which case you wouldn't even have to override self, so it simplifies as </p>

<pre><code>class MyList(list):

    @property
    def first(self):
        # TODO: catch empty list exception
        return self[0]
</code></pre>

python class