[Tutor] writing methods

Terry Carroll carroll at tjc.com
Thu Feb 26 10:06:00 EST 2004


On Wed, 25 Feb 2004, Christopher Spears wrote:

> I am trying to solve the following homework
> assignment:
> 
> Using the UserDict module, create a class called
> Odict, which will be just like a dictionary but will
> "remember" the order in which key/value pairs are
> added to the dictionary. (Hint: Override the built-in
> __setitem__ method.) Create a new method for the Odict
> object called okeys, which will return the ordered
> keys. 
> 
> I don't expect to get the answer, but I would like to
> be pointed in the right direction.  I think my major
> problem is that concepts that surround writing methods
> are still not transparent to me.  I find myself
> spending a lot of time staring at the UserDict module
> code,

Looking at the UserDict code probably won't help.  

I think you're looking at the intro to the problem ("Using the UserDict 
module...") and interpreting this as meaning that you should start with 
the UserDict module's code, and write a new class using it.  I don't think 
so.  I think it means that you should define a new class, subclassing from 
UserDict, i.e., the class definition line should look like this (I don't 
think I'm giving anything away here):

   import UserDict
   def Odict(UserDict.UserDict):
      [more stuff here]

The problem continues, "(Hint: Override the built-in __setitem__ method.)"
Okay, UserDict operates by maintaining a dictionary named "data" that 
includes the dictionary-type stuff.   __setitem__ adds an entry.  You'd 
have to add that entry (most easily by calling UserDict.__setitem__) *and* 
also maintain some additional structure that tracks the order.

This assignment is not a no-brainer, but I suspect it's one of those 
things that you either get or don', and once the light bulb flashes, 
you'll get it completely.

You're not asking for code (as you shouldn't), but here is a general 
approach I would use to take this on:

 1) Override __init__, and set up another structure to track in addition
to self.data, used to track the order in which things are added (probably
a list, could be done other ways; make sure you invoke the __init__ you're
overriding so it does its work, too). 
 2) Override __setitem__, so that it updates your structure, in addition
to invoking UserDict's __setitem__ to do the add. 
 3) "Create a new method for the Odict object called okeys, which will
return the ordered keys" using that structure.

> Is there a good tutorial or something on the web that will clear these
> concepts ups for me?

Plenty; great starting points are <http://www.python.org/topics/learn/> 
and <http://www.python.org/doc/Intros.html>.

Good luck!






More information about the Tutor mailing list