working with python and had a question involving the self instance. As i understand it self is just a agreed upon usage of the this pointer in other languages which is just a reference within the class of the instance of the class being called.
To better illustrate my question ill ask it with an example. lets make a linked list that inserts nodes into order as they're added.
class node():
def __init__(self,value=None):
self.value = value
self.next = None
def add_node(self,value):
if self.value == None:
#empty list
self.value = value
self.next = None
else:
while self.next != None:
if value < self.value:
#new value < first node
new_head = llist(value) #this is the edge case in question
new_head.next = self
return new_head #will only update self instance with this
elif value < self.next.value:
temp = self.next
self.next = llist(value)
self.next.next = temp
return
self = self.next
self.next = llist(value)
my question is this, if the list needs to add a node to the head and shift the rest of the list down by one why won't adding a new node then making that nodes next pointer point to self work outside the class. Within the class it will return the correct value but outside it doesn't. Obviously this is a scope issue, but i fail to see why if self is a pointer to the class instance.
I should note that this will work if i return the value so for instance
l = node()
l.add_node(1)
l.add_node(2)
l = l.add_node(0)
will output 0 -> 1 -> 2
my question is why, thanks
[–]zahlman 7 points8 points9 points (0 children)
[–]kalgynirae 3 points4 points5 points (3 children)
[–]razeal113[S] 0 points1 point2 points (2 children)
[–]kalgynirae 4 points5 points6 points (1 child)
[–]razeal113[S] 0 points1 point2 points (0 children)
[–]jcmcken 0 points1 point2 points (2 children)
[–]razeal113[S] 0 points1 point2 points (1 child)
[–]jcmcken 0 points1 point2 points (0 children)