Iterator for Custom Sequence
Patrick W
csposting at yahoo.com.au
Tue Jul 16 09:28:22 EDT 2002
Jonathan Hogg <jonathan at onegoodidea.com> writes:
> I'm not sure why you've used a nested function.
Relic of an early misunderstanding.
At first I thought __iter__ was supposed to *return* a generator, so I
made it a nested function and handed it to the caller. When that
didn't work, I made __iter__ *call* the nested generator. I should
then have realised that __iter__ could *be* the generator, but for
some reason I didn't.
(Instead I was off chasing red herrings, wondering whether the
generator ought to be a nested function, class method or free
function. Ridiculous in hindsight, but such is life).
> I would have written this simply as:
>
> class LinkedList:
> ....
> def __iter__(self):
> node = self.head
> while node.next is not None:
> yield node.data
> node = node.next
> ....
That's lovely. Thanks.
More information about the Python-list
mailing list