[Tutor] Advantage of subclassing UserDict and UserList
Kirby Urner
urnerk@qwest.net
Thu, 29 Nov 2001 08:22:23 -0800
Andrei Kulakov:
>Yes, you can for example make ordered dict:
>
>class SortedDict(UserDict.UserDict):
> """Sorted dictionary for dict of directories"""
> def keys(self):
> l = self.data.keys()
> l.sort()
> return l
> def items(self):
> l = self.data.items()
> l.sort()
> return l
Note that in 2.2 you can subclass list and dictionary
directly (though I think in 2.2b2 it's dict). E.g.
class SortedDict(dictionary):
_keys = dictionary.keys
_items = dictionary.items
def keys(self):
L = self._keys()
L.sort()
return L
def items(self):
L = self._items()
L.sort()
return L
>>> b = SortedDict({'D':9,'C':2,'A':1, 'E':5,})
>>> b._items()
[('A', 1), ('C', 2), ('E', 5), ('D', 9)]
>>> b.items()
[('A', 1), ('C', 2), ('D', 9), ('E', 5)]
>>> b._keys()
['A', 'C', 'E', 'D']
>>> b.keys()
['A', 'C', 'D', 'E']
Kirby