Search code examples
pythongetattrsetattr

python object style access for dictionaries ; cant figure it out


class ObjectDict(dict):
    """ allows object style access for dictionaries """

    def __getattr__(self, name):
        if name in self:
            return self[name]
        else:
            raise AttributeError('No such attribute: %s' % name)

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

    def __delattr__(self, name):
        if name in self:
            del self[name]
        else:
            raise AttributeError('No such attribute: %s' % name)

can someone explain this code for me ? I'm just a python beginner.


Solution

  • __getattr__ is for when you want to get a data.

    __setattr__ is for when you want to set a data.

    __delattr__ is for when you want to del a data.

    Now, the methods should be quite clear.

    def __getattr__(self, name):
        # if the key exists... return it.
        if name in self:
            return self[name]
        # if not : raise an error.
        else:
            raise AttributeError('No such attribute: %s' % name)
    
    def __setattr__(self, name, value):
        # set VALUE as value, with NAME as key in the dict.
        self[name] = value
    
    def __delattr__(self, name):
        # if the key "name" exists in the dictionnary... delete it
        if name in self:
            del self[name]
        # else, it doesnt exist, so cant delete it.
        else:
            raise AttributeError('No such attribute: %s' % name)