By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,156 Members | 1,026 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,156 IT Pros & Developers. It's quick & easy.

Enjoying Inheritance and operator Overloading

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
>
def __delitem__(self, item): # deleting a keyword
key = item.lower()
if not self.has_key(key):
raise KeyError(item)
dict.__delitem__(key)
Oops - except dict.__delitem__ ought have both self and item as arguments....

Regards,
Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html


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

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.