object attributes from a dictionary

Peter Otten __peter__ at web.de
Tue Jul 13 18:42:59 EDT 2004


Darren Dale 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.)

The most direct way is:

>>> class pupa:
...     def __init__(self, d):
...             self.__dict__ = d
...
>>> larva = {"a": 1, "b": 2}
>>> moth = pupa(larva)
>>> moth.a
1
>>> moth.c = 3
>>> larva
{'a': 1, 'c': 3, 'b': 2}
>>> larva["x"] = 5
>>> moth.x
5

So every change in moth affects larva and vice versa. If that is too direct,
change the initializer to update instead of rebind __dict__:

>>> class pupa2:
...     def __init__(self, d):
...             self.__dict__.update(d)
...
>>> moth2 = pupa2(larva)
>>> moth2.c
3
>>> moth2.d = 4
>>> larva
{'a': 1, 'x': 5, 'c': 3, 'b': 2} # no "d" key
>>>

Peter




More information about the Python-list mailing list