dynamically naming fields?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Darren Dale

    dynamically naming fields?

    I am transitioning from Matlab and am not very literate in Python
    terminology....

    I want to load data from a file, and I want to use the header to name my
    fields... for example, I have a file containing "time counter" in the
    header, how do I create Sample.time and Sample.counter? In Matlab it
    would be Sample.(string)

    thanks,
    Darren
  • Scott David Daniels

    #2
    Re: dynamically naming fields?

    Darren Dale wrote:
    [color=blue]
    > I want to load data from a file, and I want to use the header to name my
    > fields... for example, I have a file containing "time counter" in the
    > header, how do I create Sample.time and Sample.counter? In Matlab it
    > would be Sample.(string)
    >
    > thanks,
    > Darren[/color]

    setattr(anobjec t, name, value) sets the name field to value.
    getattr(anobjec t, name) retrieves that value.


    I find the following class useful for interactive work:

    class Data(object):
    def __init__(self, **kwargs):
    self.__dict__.u pdate(kwargs)
    def __repr__(self):
    return '%s(%s)' % (self.__class__ .__name__, ', '.join(
    ['%s=%r' % keyval for keyval in self.__dict__.i tems()]))

    # This class allows me to see data in the object. Either printing
    # the object or viewing it as a value with idle or the interactive
    # interpreter will now display data added to the object.

    sample = Data(version=1) # illustrating fields built at creation

    setattr(sample, 'time', [1,3,5])
    setattr(sample, 'counter', [12,55,93])

    print sample # illustrate the __repr__ magic to see the data


    --
    -Scott David Daniels
    Scott.Daniels@A cm.Org

    Comment

    Working...