Getting a dictionary from an object
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sat Jul 23 09:22:21 EDT 2005
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.
That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?
> The following works, but I would prefer to use a built-in way if one
> exists. Is there one?
>
> Thanks in advance.
>
> class dictobj(dict):
> """
> class dictobj(dict):
> A dictionary d with an object attached to it,
> which treats d['foo'] as d.obj.foo.
> """
> def __init__(self, obj):
> self.obj = obj
> def __getitem__(self, key):
> return self.obj.__getattribute__(key)
I don't think this is particularly useful behaviour. How do you use it?
py> D = dictobj("hello world")
py> D
{}
py> D.obj
'hello world'
py> D["food"] = "spam"
py> D
{'food': 'spam'}
py> D["food"]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in __getitem__
AttributeError: 'str' object has no attribute 'food'
--
Steven.
More information about the Python-list
mailing list