Python Classes and dynamic class members

James Stroud jstroud at mbi.ucla.edu
Sat Nov 4 05:50:22 CET 2006


acatejr at gmail.com wrote:
> James Stroud wrote:
> 
>>acatejr at gmail.com wrote:
>>
>>>I have a text file that I am parsing.  Each line is of the form:
>>>
>>>max_time  0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12
>>>
>>>The first item is the field name and the next twelve items are values
>>>for each month in the year.  There are multiple lines each for some
>>>different variable.  I am able to parse this data easily enough, but
>>>what I'd like to do is have a class that stores all this infomormation
>>>using dynamic member attributes/fields and the resulting list of
>>>values.  For example, if the class WeatherData was instantiated and I
>>>parsed the line above as so:
>>>
>>>field_name = "max_time;
>>>values = [0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12]
>>>
>>>how could I get weather data to store values in an attribute called
>>>"max_time"?  Ultimately, something like this would be possible:
>>>
>>>
>>>
>>>>>>WeatherData.max_time
>>>>>>[0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12]
>>>
>>>
>>>Any help would be appreciated.
>>>
>>
>>setattr(Weatherdata, "max_time", max_time)
>>
> Thanks a lot!!
> 
> I did find that creating and calling the following method works too:
> 
> def setAt(self, field, data):
>     expression = "self." + field + " = data"
>     exec(expression)
> 
> I just don't know which one would be more efficient, but I like setattr
> better.
> 

You have good taste. You probably want to steer away from exec() if you 
ever have the inclination. Python usually has an "approved", or 
pythonic, way of solving problems you may want to address with exec().

James


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list