[Tutor] creating a dict-like class - asigning variables... this one may take some thought ; )
spir
denis.spir at free.fr
Thu May 28 13:43:47 CEST 2009
Le Thu, 28 May 2009 03:47:09 -0700 (PDT),
"John [H2O]" <washakie at gmail.com> s'exprima ainsi:
>
> 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):
What you're looking for is a dictionary...
s = {"cheese":"Brie", "country":"France", ...}
Or maybe a kind of object type that works ~ like a dict, but with object syntax (get rid of {} and "" for keys). Example:
class Stuff(object):
def __iter__(self):
return iter(self.__dict__.items())
def items(self):
return self.__dict__
stuff = Stuff()
stuff.cheese="Brie"
stuff.country="France"
print stuff.cheese, stuff.country
print stuff.items()
for st in stuff:
print " ", st
==>
Brie France
{'cheese': 'Brie', 'country': 'France'}
('cheese', 'Brie')
('country', 'France')
Denis
------
la vita e estrany
More information about the Tutor
mailing list