dynamically naming fields?
Scott David Daniels
Scott.Daniels at Acm.Org
Wed Apr 28 11:39:40 EDT 2004
Darren Dale wrote:
> 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
setattr(anobject, name, value) sets the name field to value.
getattr(anobject, name) retrieves that value.
I find the following class useful for interactive work:
class Data(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(
['%s=%r' % keyval for keyval in self.__dict__.items()]))
# 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 at Acm.Org
More information about the Python-list
mailing list