Enjoying Inheritance and operator Overloading

Fuzzyman michael at foord.net
Mon Mar 15 12:53:09 CET 2004


I've been programming in python for a few months now - and returning
to programming after a gap of about ten years I've really enjoyed
learning python.

I've just made my first forays into inheritance and operator
overloading (both concepts that I initially found hard to grasp).

I've written a simple config file parser - and I thought I'd
experiment with making the interface easier by subclassing dict and
overloading the __setitem__, __getitem__ and __delitem__ methods......

The thing is I'm not 100% certain that what I've done is good python -
or even valid python.

As an example (my config parser is a bit more complex) I've shown my
technique for creating a 'case insensitive' dictionary... and would
welcome comments.

class lowerDict(dict):
    """A case insensitve dictionary. It converts the key to lowercase
when
    'getting', 'setting' or 'deleting' an item.
    May not work with pop or other methods."""
    def __init__(self):
        dict.__init__(self)

    def __setitem__(self, item, value):             # setting a
keyword
        item = item.lower()
        dict.__setitem__(self, item, value)

    def __getitem__(self, item):
        """To implement lowercase keys."""
        key = item.lower()
        return dict.__getitem__(self, key) 

    def __delitem__(self, item):                # deleting a keyword
        key = item.lower()
        if not self.has_key(key):
            raise KeyError(item)
        dict.__delitem__(key)


if __name__ == '__main__':
    a = lowerDict()
    a['HELLO'] =3
    print a



More information about the Python-list mailing list