[Tutor] Data Type with Dictionary and List Behavior
John Fouhy
john at fouhy.net
Tue Mar 28 02:33:46 CEST 2006
On 28/03/06, Carroll, Barry <Barry.Carroll at psc.com> wrote:
> 1. Access by name (dict)
> 2. Access by position (list)
> 3. Addition of new items (dict, list)
> 4. Set a 'last used' item (??????)
> 5. Set a 'default' item (dict???)
Probably your best bet is to define your own container class. If you
define __getitem__, you can use [] with instances of your class, just
like lists or dicts.
Something like this, perhaps (untested):
class MaskDict(UserDict.DictMixin):
def __init__(self):
self.keys = []
self.data = {}
self.default = None
def __getitem__(self, key):
if isinstance(key, (int, long)):
self.default = self.keys[key]
return self.data[self.default]
else:
self.default = key
return self.data[key]
def __setitem__(self, key, value):
try:
self.keys.remove(key)
except ValueError:
pass
self.keys.append(key)
self.data[key] = value
def __delitem__(self, key, value):
del self.data[key]
self.keys.remove(key)
def keys(self):
return self.keys
def setDefault(self, key):
self.default = key
HTH!
--
John.
More information about the Tutor
mailing list