Python : why doesn't a.pop() modify the list (custom linked-list class)
<p>I'm trying to define a class Hlist of linked lists as below:</p>

<pre><code>class Hlist:

def __init__(self, value, hlnext):
    self.value = value
    self.hlnext = hlnext

def pop(self):
    res = self.value
    if not(self.hlnext == None):
        self = self.hlnext
    return res

def __repr__(self):
    return (str(self.value) + ' - ' +  str(self.hlnext))
</code></pre>

<p>When I test the pop() method on </p>

<pre><code>a = Hlist(1, Hlist(2, None))
</code></pre>

<p>Python returns 1 - 2 - None, ok. Then</p>

<pre><code>a.pop()
</code></pre>

<p>returns 1, fine. However : </p>

<pre><code>print(a)
</code></pre>

<p>returns 1 - 2 - None. The list hasn't been modified despite</p>

<pre><code>self = self.hlnext
</code></pre>

<p>Is self the pointer a or is it another pointer pointing to the same address as a?
And why does the following code return the expected answer for pop():</p>

<pre><code>class Hlist:

def __init__(self, value, hlnext):
    self.value = value
    self.hlnext = hlnext

def pop(self):
    res = self.value
    if not(self.hlnext == None):
        self.value = self.hlnext.value
        self.next = self.hlnext.hlnext
    return res

def __repr__(self):
    return (str(self.value) + ' - ' +  str(self.hlnext))
</code></pre>

<p>is it due to the setattr function used by python?</p>

<p>Actually i was trying to get the equivalent in Python of the following class in Java : </p>

<pre><code>class Hlist{
    int value;
    Hlist hlnext;

    Hlist(int value,Hlist hlnext){
        value = value;
        hlnext = hlnext;
    }
}
</code></pre>

<p>and add a pop() method to it. In a pop() method, will Java's <code>this</code> work the same way Python's <code>self</code> does (local variable) or will it be binded to the pointer a I called pop()? In that case, will <code>this = this.hlnext</code> change the <code>a</code> pointer or not?</p>

<p>Because <code>self</code> isn't working the way you think it is. <code>self</code> is just another local variable: assigning to it inside <code>pop()</code> won't change the object into another thing. See <a href="http://stackoverflow.com/questions/28531939/python-assignment-to-self-in-constructor-does-not-make-object-the-same">this question</a> for more details.</p>

python pointers linked-list