[Tutor] creating a dict-like class - asigning variables... this one may take some thought ; )

John [H2O] washakie at gmail.com
Thu May 28 12:47:09 CEST 2009


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!

-- 
View this message in context: http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-tp23759398p23759398.html
Sent from the Python - tutor mailing list archive at Nabble.com.



More information about the Tutor mailing list