質問

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:

def __setattr__(self, name, value):
    super(MyStore, self).__setattr__(name, value)
    self._data[name] = value

However, you could save yourself a lot of hassle by just subclassing something like dict:

class MyStore(dict):

    def __init__(self, data):
        for d in data:
            self[d] = d.upper()

    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        self[name] = value

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
store.qux = 'QUX'
print "Get qux item:", store['qux']
print "Get qux attribute:", store.qux
print "'qux' is in store:", 'qux' in store

which outputs...

Store items: ['eggs', 'foo', 'bar', 'spam']
Number of items: 4
Get item: FOO
Get attribute: FOO
'foo' is in store: True
Get qux item: QUX
Get qux attribute: QUX
'qux' is in store: True
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top