"Variable variable name" or "variable lvalue"

Steve Holden steve at holdenweb.com
Sun Aug 19 20:37:29 EDT 2007


Gary Herron wrote:
> inmmike at gmail.com wrote:
>> On Aug 15, 1:42 pm, mfglinux <mfgli... at gmail.com> wrote:
>>   
>>> Hello to everybody
>>>
>>> I would like to know how to declare in python a "variable name" that
>>> it is in turn a variable
>>> In bash shell I would wrote sthg like:
>>>
>>> for x in `seq 1 3`
>>> do
>>>   M$i=Material(x)  #Material is a python class
>>> done
>>>
>>> Why I need this? Cause I have a python module that obliges me to build
>>> a variable called Period, which should have a variable name of
>>> summands (depends on the value of x)
>>>
>>> #Let's say x=3, then Period definition is
>>> Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a
>>> python class
>>>
>>> I dont know how to automatize last piece of code for any x
>>>
>>> thank you
>>>
>>> Marcos
>>>     
>> Regardless of whether or not this is a "best practice" sometimes it is
>> necessary. For example, I am looping through a dictionary to set some
>> class properties. Anyway, here is what I finally came up with:
>>
>> exec "self.%s = '%s'" % (item, plist[item])
>>   
> Yuck!  Not at all necessary.  Use setattr instead:
> 
>    setattr(self, item, plist[item])
> 
> That's much cleaner then an exec or eval.  You may also find getattr and
> hasattr useful.
> 
Or even, in some cases,

     self.__dict__.update(otherdict)

if you have a dictionary of stuff to put into an object.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list