Python-list Digest, Vol 27, Issue 123
Fredrik Lundh
fredrik at pythonware.com
Fri Dec 9 02:55:44 EST 2005
Michael Williams wrote:
> Thanks, Heiko, I'll give this a try. In the meantime, I'll try to
> explain what exactly I mean.
>
> Basically, I want the ability to reference a variable just as I am
> able to set a variable (or attribute) on the fly. For instance, say
> the user has the following list in a text file:
>
> [butter, cream, eggs, toast, jam]
list of what? what's butter? a variable? a string? did you mean
["butter", "cream", "eggs", "toast", "jam"]
or did you mean something else? (probably something else, since
whatever the user has put in the text file seems to have a value
property in your later examples).
> I want to be able to loop through that and say the following:
>
> item.__setattr__(list[0].value,myclass())
that's spelled
setattr(item, list[0].value, myclass())
in python.
to add attributes for all items in the list, do:
for v in list:
setattr(item, v.value, myclass())
if the list contains strings, you can simply do:
for v in list:
setattr(item, v, myclass())
> At that point I have item.butter, but I don't want to have to know
> (or hardcode) this, I want to then be able to do the following:
>
> item.__getattr__(list[0].value).__setattr__(list[1].value)
so the list is in fact a path? how about
this = item
for v in list[:-1]:
this = getattr(this, v)
setattr(this, list[-1], myclass())
hope this helps!
</F>
More information about the Python-list
mailing list