H.M.
H.M.

Reputation: 261

Python : why doesn't a.pop() modify the list (custom linked-list class)

I'm trying to define a class Hlist of linked lists as below:

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))

When I test the pop() method on

a = Hlist(1, Hlist(2, None))

Python returns 1 - 2 - None, ok. Then

a.pop()

returns 1, fine. However :

print(a)

returns 1 - 2 - None. The list hasn't been modified despite

self = self.hlnext

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():

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))

is it due to the setattr function used by python?

Actually i was trying to get the equivalent in Python of the following class in Java :

class Hlist{
    int value;
    Hlist hlnext;

    Hlist(int value,Hlist hlnext){
        value = value;
        hlnext = hlnext;
    }
}

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

Upvotes: 2

Views: 216

Answers (2)

romain-aga
romain-aga

Reputation: 1561

It's moslty because you can't change self directly.
If you think about pointers, you can't change the pointer address, except if you use a pointer on this pointer. Here, if you consider self as a pointer, when you assign another value to self, you don't really change the self pointer.

See this answer

The second code "works" (not in all cases), because you aren't changing self itself, but the references on which it's pointing. Then your instance is updated to remove its old value and update itself with the next value.

Upvotes: 0

kfb
kfb

Reputation: 6532

Because self isn't working the way you think it is. self is just another local variable: assigning to it inside pop() won't change the object into another thing. See this question for more details.

Upvotes: 1

Related Questions