[Tutor] iterator question for a toy class
Marcus Goldfish
magoldfish at gmail.com
Sat Apr 23 19:47:31 CEST 2005
> - As Rich pointed out, making Foo into it's own iterator by adding a next()
> method is not a good idea. A simple way to define your own iterator is to
I see that an iterator is conceptually distinct from the container
object it iterates over, but I am confused that both the iterator and
container implement __iter__() to support the iterator protocol. In
my original Foo implementation, __iter__() returned a list, which
supports the iterator protocol, so it "just worked" (albeit not for
all cases, and not efficiently). In general, though, how would I
implement my own iterator (not using generator functions)? Would I
have to have a FooIterator class? What would FooIterator.__iter__()
return?
> make __iter__() into a generator function like
... so gfs look much easier! This is the first concrete use for gf's
I've found in my code so far, and it rocks-- is it always possible to
implement an iterator using gfs? Is there a performance issue to be
aware of when using gfs?
> you want. A simple definition for __eq__() that finds these unequal would be
> def __eq__(self, other):
> return self.head == other.head and self.tail == other.tail
Ok, I like the modified __eq__(), but now I want my Foo class to store
the head and tail lists as private attributes (self.__head,
self.__tail). Is it pythonic to modify the __eq__() method to:
def __eq__(self, other):
return self.__head == other._Foo__head and self.__tail == other._Foo__tail
or is this too restrictive (e.g., perhaps I wish to compare a Foo and
Bar class as correlated list sequences. It is likely that
other._Foo__head will fail for a Bar).
> - If you define __eq__() you should also define __ne__(). Alteratively you can
... because it seems that Foo1 != Foo2 will fail otherwise. Why is that?
Thanks (you too, Rich) for the very helpful comments!
Marcus
More information about the Tutor
mailing list