dynamically naming fields?

D

Darren Dale

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
 
S

Scott David Daniels

Darren said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,189
Messages
2,571,016
Members
47,616
Latest member
gijoji4272

Latest Threads

Top