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?