On Thu, May 28, 2009 at 6:47 AM, John [H2O] <washa...@gmail.com> wrote: > > Hello, I am trying to create a class to hold and reference things similar to > matlab's structure. > > ## A class definition to hold things > class stuff(object): > """ holds stuff """ > def __init__(): > pass > �...@classmethod > def items(cls): > stuff = [] > for i in cls.__dict__: > if i[:1] != '_' and i != 'items': > stuff.append((i,cls.__dict__[i])) > return stuff > > Then in my code I would like to be able to do the follow: > > s = stuff > s.cheese = "Brie" > s.country = "French" > s.age = 2 > > and so on... > > In Ipython, as above it does work. Now here is the tricky part. I'm reading > in binary data from unformatted Fortan output. My present approach is as > follows (recommended suggestions welcome): > > f2=file(filename,'rb') > #Define names and create Dictionary Keys > I = {0:'rl0', 1:'ibdate', 2:'ibtime', 3:'version',\ > 4:'rl1', 5:'loutstep', 6:'loutaver', 7:'loutsample',\ > 8:'rl2', 9:'outlon0', 10:'outlat0', 11:'numxgrid',\ > 12:'numygrid', 13:'dxout', 14:'dyout', 15:'rl3', 16:'numzgrid',\ > } > #define the format for binary reading first part of the header file > Dfmt=['i','i','i','13s','2i','i','i','i','2i','f','f','i','i','f','f','2i','i'] > if f2: > #print filename + ' has been opened' > a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] > > # Now I want to put them into my stuff class: > for j in range(len(a)): > cmd = "h.%s = a[%s][0]" % (I[j],j) > eval(cmd) > > > But I get an error: > eval(cmd) > File "<string>", line 1 > h.rl0 = a[0][0] > ^ > SyntaxError: invalid syntax > > Thoughts? Must be something simpler or more 'pythonic' > > Thanks!
For what it's worth, you might want to have a look at NumPy/SciPy <http://www.scipy.org/> unless you have some other motive. Their structured or record arrays behave in much the way you are describing and can handled binary data (or matlab data). This also might be of interest <http://www.scipy.org/NumPy_for_Matlab_Users>. Cheers, Skipper _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor