How to overide "for line in file:"
Shalabh Chaturvedi
shalabh at cafepy.com
Sat Feb 21 22:38:57 EST 2004
David Morgenthaler wrote:
> How does one overide the iterator implied by the construct "for line
> in file:"?
>
'for' uses __iter__().
Subclass file and redefine __iter__(self). It should return an object that
has the next() method which returns the next item, or raises StopIteration
if finished. Returning self from __iter__() is ok (then you can put the
next() in the same class).
An easier alternative is to make __iter__() a generator function (so calling
it automatically returns a 'generator' object, which has next() on it, and
also raises StopIteration when done).
HTH,
Shalabh
More information about the Python-list
mailing list