Enjoying Inheritance and operator Overloading

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fuzzyman

    Enjoying Inheritance and operator Overloading

    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__(s elf)

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

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

    def __delitem__(sel f, item): # deleting a keyword
    key = item.lower()
    if not self.has_key(ke y):
    raise KeyError(item)
    dict.__delitem_ _(key)


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

    #2
    Re: Enjoying Inheritance and operator Overloading

    >[color=blue]
    > def __delitem__(sel f, item): # deleting a keyword
    > key = item.lower()
    > if not self.has_key(ke y):
    > raise KeyError(item)
    > dict.__delitem_ _(key)
    >[/color]
    Oops - except dict.__delitem_ _ ought have both self and item as arguments....

    Regards,


    Fuzzy



    [color=blue]
    >
    > if __name__ == '__main__':
    > a = lowerDict()
    > a['HELLO'] =3
    > print a[/color]

    Comment

    Working...