I’m trying to make a Link-List Node class for a Link-List, as shown in the code:
class LNode:
def __init__(self, data=None, pnext=None):
self.data = data
self.pnext = pnext
def __str__(self):
return f"{self.data} -> {self.pnext}"
def __repr__(self):
return f"{self.data} -> {self.pnext}"
def __len__(self):
print("len method called...")
cnt = 1
return cnt
def headInsert(self, nextNode):
nextNode.pnext = self.pnext
self.pnext = nextNode
def headInsert_woh(self, nextNode):
nextNode.pnext = self
return nextNode
def tailInsert(self, nextNode):
print("tail-insert called...")
tail = self
while tail.pnext:
tail = tail.pnext
tail.pnext = nextNode
return self
def __add__(self, other):
return self.tailInsert(other)
After definition, I tried codes below:
a = LNode(1)
for i in range(2, 6):
a += LNode(i)
print(a)
Strangely, __len__ method will be called repeatedly and recursively when the tail-insert method is called, or when the node pointer of the Link-List node moves. As shown below:
tail-insert called......
tail-insert called......
len method called......
tail-insert called......
len method called......
len method called......
tail-insert called......
len method called......
len method called......
len method called......
1 -> 2 -> 3 -> 4 -> 5 -> None
But why? I thought __len__ is the implementation of BIF len(), why it will be called here? Thanks a lot.
This is because you’re testing the truthiness of
tail.pnext
as awhile
condition in this line:According to Python’s documentation of Truth Value Testing: