typechecks: just say no! (was Re: Determining Types)
Guido van Rossum
guido at python.org
Sun Sep 9 07:38:50 CEST 2001
ullrich at math.okstate.edu (David C. Ullrich) writes:
> But in other places it's good to be able to refer to
> fields with non-literal names, so I add a __getitem__
> so that rec['thisfield'] returns rec.thisfield.
> (Actually the main reason I want this is so that I
> can use a Rec as a mapping in a string format thing:
> 'Your name is %(Name)s' % rec)
> 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
> return (fieldname, getattr(self, fieldname))
> if index is an integer.
In 2.2, you can define an iterator rather than overloading __getitem__.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list