This seems like a bug to me where I couldn't really figure it out why.
I have a very simple self-defined LinkedList class:
class MyLinkedList:
def __init__(self):
self.head = None
def __iter__(self):
self.currNode = self.head
return self
def __next__(self):
if self.currNode:
res = self.currNode
self.currNode = self.currNode.next
return res
else:
raise StopIteration
def addAtHead(self, val: int) -> None:
currNode = self.head
self.head = Node(val, currNode)
The problem comes inside iter method. After I added a node at head to a empty linkedList, the iter still think the self.head is None! In debug node, I can see self.head is a valid not none instance, but after assigning its value to self.currNode, self.currNode turns out to be None.
I thought it can be a problem of property issue so I changed the attribute to a property. But the problem still exists. Where am I wrong?
@property
def head(self):
return self._head
@head.setter
def head(self, x):
self._head = x
Adding my calling stack:
ll = MyLinkedList()
ll.addAtTail(6)
ll.addAtHead(5)
ll[0] # is None
#where a __getitem__ is defined as:
def __getitem__(self, i):
n = 0
for node in self:
if n == i:
return node
n += 1
raise IndexError
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next

head = {Node} .... At any rate, can you show an example of trying to use the class that causes an unexpected error? IDEs don't always get everything right, or they may show things out of sync.__iter__methods (in 99.99% of cases they should do nothing butreturn self), as Python assumes it can blithely call__iter__on an existing iterator and change nothing. If you want this to be an iterable,__next__should not be defined, and, usually, you write__iter__as a generator function (migrating all the logic into__iter__and usingyieldwhere__next__would usereturn).MyLinkedListclass from your first block with the addition of the__getitem__method in your last block. I also created theNodeclass from your last block. Then the rest of the code in the last block worked fine. I get a node when I doll[0].