Can one get "for x in y" to work for non builtin classes?
M.-A. Lemburg
mal at egenix.com
Mon Mar 3 06:17:39 EST 2008
On 2008-03-02 15:06, Preben Randhol wrote:
> Hi
>
> I'm making a kind of ordered dictionary class. It is not exactly a
> dictionary, but it uses a list and dictionary to store the data.
>
> Something like:
>
> class dbase(list):
> '''Database class keeping track of the order and data'''
>
> def __init__(self):
> self.__data = {}
> self.__order = []
> self.__uniq_id = 0
>
> I'm just wondering if it is possible to get my class to work so that if
> one do:
>
>
> d=dbase()
> d.append("Data")
> d.append([1,2])
>
> one can do like this to iterate over the data.
>
> for x in d:
> ...
>
> I'm looking at the list class but I don't quite understand from pydoc
> which __ __ methods I have to implement to get the above to work.
The easiest is to implement an iterator which then get's
returned by the .__iter__() method.
http://www.python.org/doc/lib/typeiter.html
It's also possible to implement .__getitem__() and .__len__()
methods and have Python create an iterator on-the-fly. That's
how Python used to work before iterators were added to the
language.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Mar 03 2008)
>>> Python/Zope Consulting and Support ... http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________
:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
More information about the Python-list
mailing list