-4
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.

DavidG
  • 21,958
  • 13
  • 81
  • 76
Arjun Biju
  • 63
  • 9

2 Answers2

2

An ObjectDict instance is a regular dictionary via class inheritance. See ObjectDict(dict)

The __getattr__ magic function allows for the definition of dot-notation access for any object. And it simply calls normal dictionary access here

Similarly, __setattr__ and __delattr__ allows setting and deleting (using Python's del expression) values from dot-notation. However, to set nested values, you need the value of the first key to also be an ObjectDict

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
1

__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)
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
IMCoins
  • 2,983
  • 1
  • 9
  • 23