Python Classes and dynamic class members

John Machin sjmachin at lexicon.net
Fri Nov 3 18:45:39 EST 2006


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]

errrmm, WeatherData is the class, not an instance of the class. See
below.

>
> Any help would be appreciated.

class WeatherData(object):
    pass

# then, for each instance:
    wd = WeatherData()
    # for each line:
        # parse input to obtain field_name and values
        setattr(wd, field_name, values)

HTH,
John




More information about the Python-list mailing list