list element of a class with the for statement

Jeff Shannon jeff at ccvcorp.com
Tue Mar 26 14:03:42 EST 2002


Anton Vredegoor wrote:

> >because I would like to write something like:
> >
> >db=CRdb()
> >for entry in db:
> >       print entry
>
> .......
> class CRdb:
>
>     def __init__(self):
>         self.__fieldsName= []
>         self.__keyname= []
>         self.__records   = ['first','secnd','third']
>         self.__iRecord= 0
>
>     def __getitem__(self,i):
>         return self.__records[i]
>

Of course, if you're going this route, it's probably best to provide a
__len__() method as well, and to deal with slices...   Another
alternative would be to derive your class from UserList.UserList -- this
will "automagically" handle list-like behavior (except that your
__records attribute will now be called data).

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list