By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,100 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

dynamically naming fields?

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Sc***********@Acm.Org
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.