[Tutor] indexing with a class
Christopher Spears
cspears2002 at yahoo.com
Fri Feb 27 19:26:11 EST 2004
I am trying to create a class in the UserDict module
that will remember the order in which I enter keys.
Here is an example of an attempt to solve this
problem:
class ODict(UserDict):
def __setitem__(self, key, item):
counter = 0
self.data[key] = item
counter = counter + 1
self.order = [(key,counter)]
The idea was to have the class generate a list of
tuples that have the key and the order that key was
entered, i.e. [('key1',1),('key2',2),...etc].
But when I went for a test run, I got this result
(UserDict2 is a copy of the UserDict module. I wanted
to work with a copy instead of the original for
safety.):
>>> import UserDict2
>>> dict = {}
>>> a = UserDict2.ODict(dict)
>>> a['test'] = 1
>>> a.order
[('test', 1)]
>>> a['another test'] = 2
>>> a
{'test': 1, 'another test': 2}
>>> a.order
[('another test', 1)]
This has been my first major stumbling block. When I
use the class, it keeps overwriting any counters, etc.
that I use.
Maybe a better way is to pass some sort of result to a
function under the ODict class? Right now, I just
have:
class ODict(UserDict):
def __setitem__(self, key, item):
counter = 0
self.data[key] = item
counter = counter + 1
self.order = [(key,counter)]
def okeys(self):
print order
This won't work, so my second stumbling block is how
to do I get this class to pass some sort of useful
result when I use the __setitem__ special method. Any hints?
More information about the Tutor
mailing list