object attributes from a dictionary

Robert Brewer fumanchu at amor.org
Wed Jul 14 00:45:22 CEST 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)

PythonWin 2.3.2 (#49, Oct  2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)]
on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>> class pupa:
... 	pass
... 
>>> pupa.__dict__
{'__module__': '__main__', '__doc__': None}
>>> larva = {'a': 1, 'b': 2}
>>> pupa.__dict__.update(larva)
>>> dir(pupa)
['__doc__', '__module__', 'a', 'b']
>>> pupa.a
1
>>> pupa.__dict__
{'a': 1, '__module__': '__main__', 'b': 2, '__doc__': None}


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list