typechecks: just say no! (was Re: Determining Types)
Marcin 'Qrczak' Kowalczyk
qrczak at knm.org.pl
Mon Sep 3 11:27:09 EDT 2001
Mon, 03 Sep 2001 14:31:04 GMT, David C. Ullrich <ullrich at math.okstate.edu> pisze:
> In yet other places I want to iterate over the fields
> of a record, as in
>
> for key, value in rec:
>
> So in __getitem__ I check the type of index, returning
> getattr(self, index) if index is a string and saying
>
> fieldname=self.__fieldnames__[index]
> return (fieldname, getattr(self, fieldname))
>
> if index is an integer.
Newer versions of Python allow to define how the object is iterated over
independently of indexing.
Define method __iter__ which returns an iterator (an object which
keeps a state, whose next method returns the next object or raises
StopIteration, and whose __iter__ method returns self).
In this case the iterator can be defined thus (untested):
def __iter__(self):
for name in self.__fieldnames__:
yield (name, getattr(self, name))
You will need
from __future__ import generators
at the top of the module.
BTW, iteration over a dictionary now yields its keys. You may consider
conforming to this convention:
def __iter__(self):
return iter(self.__fieldnames__)
--
__("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
\__/
^^ SYGNATURA ZASTĘPCZA
QRCZAK
More information about the Python-list
mailing list