Getting a dictionary from an object
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Sun Jul 24 09:01:40 EDT 2005
Thanos Tsouanas a écrit :
>>On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
>>
>>>Hello.
>>>
>>>I would like to have a quick way to create dicts from object, so that a
>>>call to foo['bar'] would return obj.bar.
>>
(snip)
> print foo %do
>
> where do is a dictobj object...
I gave you a solution based on the Decorator pattern in another post,
but there is also the possibility to add a __getitem__ method directly
to the to-be-formatted object's class:
def mygetitem(obj, name):
return getattr(obj, name)
setattr(obj.__class__, '__getitem__', mygetitem)
obj['bar']
<meta>
BTW, parts of this thread should remind us all that it's usually better
to clearly describe the *problem* before asking for comments on the
solution...
</meta>
My 2 cents...
Bruno
More information about the Python-list
mailing list