next up previous contents
Next: Iterators Up: Writing Modules Previous: Inheritance   Contents

Adding Methods to the Basic Types

While we started completely from scratch in designing methods and objects in the previous sections, many times the need for a new object can be met by simply adding one or two methods to an existing basic data type. To facilitate this, python provides the UserString, UserList and UserDict classes. These classes store a regular object in the data attribute, and allow you to quickly create new objects which have all the usual methods of a string, list or dictionary along with any new methods you care to define.

As an example, suppose we wish to create a dictionary that will ``remember'' the order in which entries are added. Of course, this could be done by explicitly keeping a list of the keys, but would be awkward to implement because each time an entry was added to the dictionary, a separate statement would be needed to update the list. By overloading the __setitem__ method, we can store each key as it is encountered; by providing a new method (say, okeys), we can retrieve the ordered list. To simplify matters, the __init__ method will not accept any arguments, so that the dictionary must be built incrementally. (When a dictionary is initialized in the usual way, the keys are added in a random order.) Here's an example of how such a dictionary could be implemented:

from UserDict import UserDict

class ODict(UserDict):
    def __init__(self):
        self._okeys = [] = {}

    def __setitem__(self,key,value):[key] = value
       if key not in self._okeys:

    def okeys(self):
       return self._okeys
After creating an object of type ODict, we can manipulate it just as any other dictionary, since, when you invoke an existing method, the UserDict class knows to operate on the data attribute of the object. However, the new okeys method is available to provide the keys in the order in which they were created:
>>> from odict import ODict
>>> mydict = ODict()
>>> words = ['cat','dog','duck','chicken','goat']
>>> for w in words:
...     mydict[w] = len(w)
>>> mydict.keys()
['goat', 'chicken', 'duck', 'dog', 'cat']
>>> mydict.okeys()
['cat', 'dog', 'duck', 'chicken', 'goat']

next up previous contents
Next: Iterators Up: Writing Modules Previous: Inheritance   Contents
Phil Spector 2003-11-12