Alternative iterator syntax
Michael Hudson
mwh21 at cam.ac.uk
Wed Feb 21 12:36:16 EST 2001
aahz at panix.com (Aahz Maruch) writes:
> In article <mailman.982769240.31345.python-list at python.org>,
> Huaiyu Zhu <hzhu at users.sourceforge.net> wrote:
> >
> > [...]
>
> I'm not sure where to put this question, so I'm just deleting all of
> Huaiyu's text.
>
> How does one get UserDict.keys (note: no parens here) to return an
> iterator? Normally this will simply return a reference to the method.
class _Keys:
def __init__(self, dict):
self.dict = dict
def __contains__(self, item):
return self.dict.has_key(item)
def __call__(self):
return self.dict.keys()
... etc ...
class UserDict:
def __init__(self, dict=None):
if data is None:
data = {}
self.data = dict
self.keys = _Keys(dict)
... etc ...
Not *very* different from how you'd implement this in C, really.
Hmm, you might want to have the _Keys object hang on the instance
rather than the dict if assigning to the .data member of UserDict is
allowed. Which would create a circular reference, but we don't have
to worry about that too much now...
Cheers,
M.
--
> Look I don't know. Thankyou everyone for arguing me round in
> circles.
No need for thanks, ma'am; that's what we're here for.
-- LNR & Michael M Mason, cam.misc
More information about the Python-list
mailing list