I’m trying to write a Python class that acts like some sort of datastore. So instead of using a dictionary for example, I want to access my data as class.foo and still be able to do all the cool stuff like iterate over it as for x in dataclass.
The following is what I came up with:
class MyStore(object):
def __init__(self, data):
self._data = {}
for d in data:
# Just for the sake of example
self._data[d] = d.upper()
def __iter__(self):
return self._data.values().__iter__()
def __len__(self):
return len(self._data)
def __contains__(self, name):
return name in self._data
def __getitem__(self, name):
return self._data[name]
def __getattr__(self, name):
return self._data[name]
store = MyStore(['foo', 'bar', 'spam', 'eggs'])
print "Store items:", [item for item in store]
print "Number of items:", len(store)
print "Get item:", store['foo']
print "Get attribute:", store.foo
print "'foo' is in store:", 'foo' in store
And, apparently it works. Hooray! But how do I implement the setting of an attribute correctly? Adding the following ends up in an recursion limit on __getattr__:
def __setattr__(self, name, value):
self._data[name] = value
Reading the docs, I should call the superclass (object) __setattr__ method to avoid recursion, but that way I can’t control my self._data dict.
Can someone point me into the right direction?
Try this:
However, you could save yourself a lot of hassle by just subclassing something like
dict:which outputs…