Python 2.2, creating new types from base types

Peter Milliken peter.milliken at gtech.com
Thu Jan 17 21:26:53 EST 2002


Hi Terry,

I think this would work but "violates" the concept I have in my mind of
subclassing a type i.e. if abc is a real dictionary of dictionaries then
what do I have to do to derive the same behaviour in a "type" subclassed off
the real type? Certainly I can't find anything in the "Whats new in 2.2" or
any other documentation on the new features in 2.2 that would preclude the
syntax I am attempting - it is just a matter of being advised how to get it
working that way :-). From what I could read, any subclass of a base type
should have the same functionality available as its parent - base
dictionaries can be used in the way I am proposing so what do I have to do
to get a type derived from the base to work that way? :-).

(Obviously) I am trying for that totally "transparent" look to the code i.e.
the reader would look at the way abc is used and it wouldn't look any
differently than if it was defined as the base dict type. If I start to use
other mechanisms such as abc[('1', '2', '3')] then it defeats the purpose
and I might as well write the class in a more "standard"/conventional way
i.e. provide methods with parameter arguments etc. Which would raise some
level of disappointment in my mind as to the "new" features of 2.2 :-)

Thanks,
Peter

"Terry Reedy" <tjreedy at home.com> wrote in message
news:TeL18.776$Qc6.121175 at news1.rdc2.pa.home.com...
>
> "Peter Milliken" <peter.milliken at gtech.com> wrote in message
> news:a27hn1$tph1 at news1.gtech.com...
> > I would like to create a specialised data type that is essentially a
> > dictionary of dictionaries
> ...
> > class my_dict (dict):
> >   def __init__ (self):
> >       self.special_dict = {'1' : {'2' : {'3' : '4'}}}    # Example
> data
> >
> > Accessing the contents of an instance should (to my way of thinking
> :-)) be
> > something like this:
> >
> > abc = my_dict()
> >
> > print abc['1']['2']['3']
> >
> >
> > Now, I wasn't sure how to overload the __getitem__ def
>
> You seem to be hoping/presuming that your __getitem__() will somehow
> get all three keys at once.  It won't.  However....
>
> I believe you could access with tuple of keys and have your magic
> access function split it and work down thru the dictionary tree.  ie:
>
> print abc[('1','2','3')]
>
>   def __getitem__(self, keytuple): #UNTESTED!!!
>     value = self.special_dict
>     for key in keytuple:
>       value = value[key]
>     return value
>
> Terry J. Reedy
>
>
>
>





More information about the Python-list mailing list