referring from within containers objects

Terry Reedy tjreedy at udel.edu
Mon Mar 10 14:31:59 EST 2003


"Dimitris Garanatsios" <dg96057 at teledomenet.gr> wrote in message
news:3e6c8de7$0$6145$4d4eb98e at read.news.gr.uu.net...
> Sandy Norton wrote:
> > This is just an idea that occurred to me while working with
> > dictionaries in which the values of certain keys were composed of
the
> > values of other keys and I found that the syntax for solving that
> > problem wasn't as pretty as I would have liked.
> >
> > Here's an example:
> >
> > d = {
> >   'fname' : 'Nit',
> >   'lname' : 'Wit'
> > }
> >
> > Now I have to do this:
> >
> > d['fullname'] = d['fname'] + ' ' + d['lname']

On principle, this is a bad idea since you are storing the same data
in two different places.  This leads to the possibility (too often
realized) of inconsistent data.  If you change fname or lname or
fullname without changing the counterpart, you have a problem.  It is
better to either join fname and lname or split fullname as needed.

> For your example i would use a class definition instead of a
dictionary like
>
> class Baptize:
>      def __init__(self, fname, mname, lname):
>          self.fname = fname
>          self.mname = mname
>          self.lname = lname
>          self.fullname = fname +' '+ mname +' '+ lname
>
> and instantiate it like
>
> baby = Baptize('Pretty', 'Python', 'Syntax')

A class is a good idea, but the above still has the same problem of
consistency management.  One can use use __getattr__ and __setattr__
to get and set virtual attributes as needed.  Even better: make
Baptize a new class (subclass from object) and you can use a fullname
property that will do the catenation on demand.  This is one of the
sorts of things that properties were meant for ;-).

Terry J. Reedy






More information about the Python-list mailing list