I have a class of the node which contain his parent and want to create iterator on it. Here is my try:
class Node:
def __init__(self, parent=None):
self._parent = parent
def __iter__(self):
self = self.parent
def __next__(self):
if self.parent is None:
raise StopIteration
else:
self = self.parent
return self
But when I try to loop over the instance, it's never stops and returns the same value, what I did wrong?
self.parent?Nodeobjects, not aNodeitself.Nodeclass an iterator, you probably want to defined aNodeIteratorclass, and makeNodeand iterable, although, normally,Nodeobjects themselves wouldn't be iterable, but some container class, likeNodeListor whatever, would be iterable.__iter__method returnsNone, when it should returnselfsince you are implementing an iterator, although, you shouldn't be doing that to begin with. You should be implementing an iterable, where__iter__returns an iterator. Note,self = self.parentdoesn't have an affect on anything, it simply reassigns theselflocal variable, and then the funciton returnsNone