In class object, how to auto update attributes when you change only one entry of a list?
<p>I have seen this answer for a very similar question:</p>

<p><a href="http://stackoverflow.com/a/14916491/5726899"><em>In class object, how to auto update attributes?</em></a></p>

<p>I will paste the code here:</p>

<pre><code>class SomeClass(object):
    def __init__(self, n):
        self.list = range(0, n)

    @property
    def list(self):
        return self._list
    @list.setter
    def list(self, val):
        self._list = val
        self._listsquare = [x**2 for x in self._list ]

    @property
    def listsquare(self):
        return self._listsquare
    @listsquare.setter
    def listsquare(self, val):
        self.list = [int(pow(x, 0.5)) for x in val]

&gt;&gt;&gt; c = SomeClass(5)
&gt;&gt;&gt; c.listsquare
[0, 1, 4, 9, 16]
&gt;&gt;&gt; c.list
[0, 1, 2, 3, 4]
&gt;&gt;&gt; c.list = range(0,6)
&gt;&gt;&gt; c.list
[0, 1, 2, 3, 4, 5]
&gt;&gt;&gt; c.listsquare
[0, 1, 4, 9, 16, 25]
&gt;&gt;&gt; c.listsquare = [x**2 for x in range(0,10)]
&gt;&gt;&gt; c.list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>

<p>In this code, when I update the list using:</p>

<pre><code>&gt;&gt;&gt; c.list = [1, 2, 3, 4]
</code></pre>

<p>c.listsquare will be updated accordingly:</p>

<pre><code>&gt;&gt;&gt; c.listsquare
[1, 4, 9, 16]
</code></pre>

<p>But when I try:</p>

<pre><code>&gt;&gt;&gt; c.list[0] = 5
&gt;&gt;&gt; c.list
[5, 2, 3, 4]
</code></pre>

<p>Listsquares is not updated:</p>

<pre><code>&gt;&gt;&gt; c.listsquare
[1, 4, 9, 16]
</code></pre>

<p>How can I make listsquare auto update when I change only one item inside the list?</p>

<p>First of all I would recommend u not to change two, different attributes by accesing single list.setter. The reason why does:</p>

<pre><code>&gt;&gt;&gt; c.list[0] = 5
&gt;&gt;&gt; c.list
[5, 2, 3, 4]
&gt;&gt;&gt; c.listsquare
[1, 4, 9, 16]
</code></pre>

<p>not work, is that, you are accesing the c.list.__setitem__ method.</p>

<pre><code>c.list[0] = 5 
is equal to
c.list.__setitem__(0, 5)
or
list.__setitem__(c.list, 0, 5)
and as such, the list.__setitem__ method isn't the one you've implemented in your class.
</code></pre>

<p>However, if you really want to do so, you should reconsider creating the square list based on self._list.</p>

<pre><code>class SomeClass(object):
    def __init__(self, n):
        self.list = range(0, n)

    @property
    def list(self):
        return self._list

    @list.setter
    def list(self, val):
        self._list = val

    @property
    def listsquare(self):
        return [n ** 2 for n in self.list]

    @listsquare.setter
    def listsquare(self, val):
        self.list = [int(pow(x, 0.5)) for x in val]
</code></pre>

python class attributes