[Tutor] Use iterator to refer to an object's attribute?

Ron Britton 9bh4frs02 at sneakemail.com
Thu Apr 20 20:37:34 CEST 2006


>> I wanted to make the methods flexible enough that I wouldn't have to 
>> edit every method if the module list ever changed.  I guess I don't 
>> understand how a dictionary works in this situation.
>
> I don;t understand what you don;t understand here. Can you expand on 
> why you don't think a dictionary would work?

This remark was based on one of my earlier designs.  It didn't work 
there, so I abandoned dictionaries.  The library reference says:
"Only values containing lists, dictionaries or other mutable types 
(that are compared by value rather than by object identity) may not be 
used as keys."
This added to the problem, at least in the design I attempted it in.

>> I originally had tuples, but you can't access individual elements.
>
> What makes you think so?
>
>>>> t = (1,2,3)
>>>> print t[0]
> 1

I didn't work before when I used it as an index.  Now it does.  I must 
have done something different originally.  But you are right.  This 
works:
 >>> mylist = ['one', 'two', 'three']
 >>> t = (0,1,2)
 >>> print mylist[t[0]]
one

>>>> I have object "db.mb".  I have iterator "shortmod" with a value of  
>>>> "mb". Why can't I call "db.shortmod"?
>>>
>>> You can use db.getattr(shortmod)
>> That doesn't work.  It tells me "Database instance has no attribute 
>> 'getattr'".
>
> Its actually a special method so needs the underscores __getattr__
> and accessed via a function. I got my syntax muddled:
>
> getattr(db, shortmod)
>
> is how it should be written.

That works!  I knew there had to be a way!

Thanks for the help!
Ron



More information about the Tutor mailing list