My question is in the del_node
method, despite setting self = self.next
, this seems to have no affect on the instance of the class that's making the call.
for instance, if i have a linked list L = 1 -> 2 -> 3 -> 4
calling L.del_node(x)
, where x
is any node other than the first, simply making the call this way will work, however, if I were to call L.del_node(1)
I have to call it as L = L.del_node(1);
I'm assuming this has to do with not changing any values of the instance as I am with the others (eg resetting self.data
/ next
, etc).
I ask because I'm confused why the statement self = self.next
doesn't seem to affect the instance when self.data = ...
does.
class Node():
def __init__(self,data = None):
self.data = data
self.next = None
def add_node(self,data):
if self.data == None:
self.data = data
else:
while self.next != None:
self = self.next
self.next = Node(data)
def del_node(self,data):
if self.data == None:
print "ERROR: Null list"
return self
elif self.data == data:
if self.next == None:
self.data = None
return self
else:
#this seems to be the only case where
#instance = instance.del_node() matters (why?)
#opposed to just instance.del_node()
return self.next
start = self
prev = self
self = self.next
while self.next != None:
if self.data == data:
prev.next = self.next
return start
prev = self
self = self.next
if self.data == data:
prev.next = None
return start
else:
print "ERROR: value not in list"
return start
def get_len(self):
length = 0
if self.data == None:
return length
while self.next != None:
length += 1
self = self.next
return length + 1
def __str__(self):
string = ''
while self.next != None:
string += str(self.data) + ' -> '
self = self.next
return string + str(self.data)
self = something
does not change the object. Just as everywhere else in Python, it merely rebinds the local name self
. (There is nothing special to Python about the name self
--it's only used by convention. A method is just a normal function and self
is just a normal argument. It's how it's called that passes self
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.