Using dict as object

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Wed Sep 19 09:02:47 EDT 2012


Am 19.09.2012 12:24 schrieb Pierre Tardy:

> One thing that is cooler with java-script than in python is that dictionaries and objects are the same thing. It allows browsing of complex hierarchical data syntactically easy.
>
> For manipulating complex jsonable data, one will always prefer writing:
> buildrequest.properties.myprop
> rather than
> brdict['properties']['myprop']

This is quite easy to achieve (but not so easy to understand):

class JsObject(dict):
     def __init__(self, *args, **kwargs):
         super(JsObject, self).__init__(*args, **kwargs)
         self.__dict__ = self

(Google for JSObject; this is not my courtesy).

What does it do? Well, an object's attributes are stored in a dict. If I 
subclass dict, the resulting class can be used for this as well.

In this case, a subclass of a dict gets itself as its __dict__. What 
happens now is

d = JsObject()

d.a = 1
print d['a']

# This results in d.__dict__['a'] = 1.
# As d.__dict__ is d, this is equivalent to d['a'] = 1.

# Now the other way:

d['b'] = 42
print d.b

# here as well: d.b reads d.__dict__['b'], which is essentially d['b'].


Thomas



More information about the Python-list mailing list