classes and __iter__
Ian Kelly
ian.g.kelly at gmail.com
Mon Jan 9 18:20:32 EST 2012
On Mon, Jan 9, 2012 at 3:51 PM, david.garvey at gmail.com
<david.garvey at gmail.com> wrote:
> ... def __iter__(self):
> ... return iter(self.keylist, self.d)
This method is incorrect. The 2-argument form of iter() is very
different from the 1-argument form. Whereas the 1-argument form takes
an iterable, the 2-argument form takes a callable and a sentinel
value. In that case, iter() attempts to call the callable until the
sentinel is returned. In your code, it would attempt to call the
keylist (which would fail with a TypeError) until it returned the
dictionary as a result. This would be more in line with what you're
trying to do:
def __iter__(self):
for key in self.keylist:
yield key, self.d[key]
>>>> for key in helo.keylist:
> ... print "Key:%s Value:%s" %(key,helo.d[key])
Note that this works because you're not actually using the class's
__iter__ method here. You're iterating over the keylist directly, not
over the containing class instance.
More information about the Python-list
mailing list