[Tutor] Eureka!

Christopher Spears cspears2002 at yahoo.com
Sun Feb 29 12:59:49 EST 2004


For those not familiar with my homework problem, here
it is:

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 copied the UserDict module and created a module
called UserDict2.  Inside this module, I created the
following class and definition:

class ODict(UserDict):
    order = []
    def __setitem__(self, key, item):
        self.data[key] = item
        self.order.append(key)
    def okeys(self):
        print self.order

Here are the results:
>>> import UserDict2
>>> dict = {}
>>> a = UserDict2.ODict(dict)
>>> a['a'] = 1
>>> a
{'a': 1}
>>> a.order
['a']
>>> a['b'] = 2
>>> a
{'a': 1, 'b': 2}
>>> a.order
['a', 'b']
>>> a[(1,2)] = 3
>>> a
{'a': 1, (1, 2): 3, 'b': 2}
>>> a.order
['a', 'b', (1, 2)]

In order to access the function, do the following:
>>> UserDict2.ODict.okeys(a)
['a', 'b', (1, 2)]

What I created was basically a type of keys function. 
The order that the keys were listed in is implicit in
their position in the list.  I do have a question
though.  In the past, when I entered something like:

class ODict(UserDict):
    order = []
    def __setitem__(self, key, item):

I would get some sort of error about the order
variable.  Can anyone explain this?  I wish I remember
what I wrote, but it's all a big blur to me.  Should I
have used __init__ to declare the order variable? 
What is the purpose of __init__ anyway?

-Chris



More information about the Tutor mailing list