Question

I have browsed the web and pydoc to find my answer without success. My issue is the following:

I want to define a class with properties, as I would do habitually.

class Container(object):
    def __init__(self, content):
        assert isinstance(content, dict), "The container can only contain a dictionary"
        self._content = content

    @property
    def name():
        try:
            return self._content["its_name"]
        except KeyError:
            raise AttributeError

Now, to access the content's field "its_name", I can use container.name, with a slight modification between the field's name and the attribute's.

I would like to have a default behavior when no specific getter property is set. I mean, if I call container.description, I want my class to try returning self._content["description"], and throw an AttributeError if there is no such key. While still calling the specific property for cases like container.name.

Thanks in advance for your help.

Était-ce utile?

La solution

This is what the __getattr__ special method is for:

def __getattr__(self, attrname):
    # Only called if the other ways of accessing the attribute fail.
    try:
        return self._content[attrname]
    except KeyError:
        raise AttributeError

Note that if for some reason you try to retrieve an unknown attribute when the _content attribute doesn't exist, the line

        return self._content[attrname]

will recursively invoke __getattr__ in an attempt to get the _content attribute, and that call will call __getattr__, and so on until stack overflow.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top