The key idea in turning an object to accept dict-like access mechanism is to inherit that class from a dict and provide methods for setting, getting, and deleting the keys of the dictionary-like object.
Here's a working example
class DictLikeObject(dict):
def __init__(self):
self.a_regular_attribute = 'blah'
self['some_key'] = 'bar'
def some_method(self, arg1, **kwargs):
do_something()
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
if key in self:
return self[key]
else:
raise AttributeError("No such attribute: " + key)
def __delattr__(self, key):
if key in self:
del self[key]
else:
raise AttributeError("No such attribute: " + key)
There, you have it. You own dict like object. You can define regular attributes and methods. For example, see a_regular_attribute and some_method in the class definition above.
You can also initialize some dict-like members. For example, see see some_key.
You can also create attributes on the fly as shown in the following snippet.
dlo = DictLikeObject()
dlo['new_key'] = 'foo'