object attributes from a dictionary

Darren Dale dd55 at cornell.edu
Wed Jul 14 11:39:07 EDT 2004


John Lenton wrote:
> On Wed, 14 Jul 2004 10:51:28 -0400, Darren Dale <dd55 at cornell.edu> wrote:
> 
>>John Lenton wrote:
>>
>>>On Tue, 13 Jul 2004 18:24:49 -0400, Darren Dale <dd55 at cornell.edu> wrote:
>>>
>>>
>>>>Is there a more direct way than this to turn a dictionary into an object?
>>>>
>>>>class pupa:
>>>>    def __init__(self,initDict,*args,**kwargs):
>>>>        [setattr(self,key,initDict[key]) for key in initDict.keys()]
>>>>
>>>>larva={'a':1,'b':2}
>>>>moth=pupa(larva)
>>>>
>>>>(ok, so I'm dorking a bit here. I havent slept in two days.)
>>>
>>>
>>>    class pupa(dict):
>>>        def __getattr__(self, attr):
>>>            return self[attr]
>>>        def __setattr__(self, attr, val):
>>>            self[attr] = val
>>>
>>
>>Maybe I'm missing a step, but this doesnt work.
> 
> 
> works here :)
> 
> Python 2.3.4 (#2, Jul  5 2004, 09:15:05)
> [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
>>>>class pupa(dict):
> 
> ...    def __getattr__(self, attr):
> ...        return self[attr]
> ...    def __setattr__(self, attr, val):
> ...        self[attr] = val
> ...
> 
>>>>larva={'a':1,'b':2}
>>>>moth=pupa(larva)
>>>>moth.a
> 
> 1
> 
>>>>moth.b
> 
> 2
> 
> unless you mean something else by "this doesn't work"
> 
I see. I wasnt clear when I asked my original question. A dictionary is 
already an object. I wanted to take a dictionary and by creating a new 
object, turn the key/value pairs into object attributes.

Using Peters class definition,
larva={'a':1,'b':2}
moth=pupa(larva)
vars(moth) --> a dictionary listing attribute/value pairs.

Using your definition, John, vars(moth) yields an empty dictionary. 
Thats why I didnt think it was working, but you are right. It works, 
just not the way I looking for.



More information about the Python-list mailing list