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 need to add a call to the <code>super</code> class, and for <code>first</code> to work as expected I'd recommend a <code>property</code>:</p>

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

    @property
    def first(self):
        return self[0]

    @first.setter
    def first(self, value):
        self[0] = value
</code></pre>

<p>Now calling:</p>

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

<p>gives:</p>

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

python class