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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to