[Tutor] making object iterable

James Reynolds eire1130 at gmail.com
Sat Feb 5 21:13:20 CET 2011


You should probably read this section in the python tutorial:

http://docs.python.org/tutorial/classes.html#iterators

If you have any questions after that, I would suggest posting back here but
that should cover it.

On Sat, Feb 5, 2011 at 2:46 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> I have a class which has a list as an attribute, meaning you must say
> something like:
> for result in obj.results: ...
> I want to make life a bit easier and let users just say:
> for result in obj: ...
> Here is what I have tried to make my class into an iterable one, yet I
> get an error saying that the class does not support indexing:
>
>  def __iter__(self):
>  #makes this class indexable instead of having to use its "results" list
>  return self.iterate()
>
>  def iterate(self):
>  i=0
>  while i<len(self.results):
>   yield self.results[i]
>   i+=1
>
> I am not sure why this does not work, unless I am misunderstanding
> something about iterators and iterables? I thought an iterable, which
> is what I am shooting for, was an iterator on steroids, allowing
> indexing, multiple passes over the list, and all that. Do I want to
> make this an iterator instead of an iterable?
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110205/c9ccebc2/attachment.html>


More information about the Tutor mailing list