preference tree like in jdk 1.4
Danyel Fisher
danyelf at acm.org
Wed Feb 20 16:45:40 EST 2002
I think the container plan is on the right track.
It is fairly clear how to use setattr to do things like this.
[sketchy, only lightly tested...]
class Container:
attr_table = {}
def __getattr__( self, arg ):
if not self.attr_table.has_key( arg ):
self.attr_table[ arg ] = Container()
return self.attr_table[ arg ]
def __setattr__( self, arg, val ) :
self.attr_table[ arg ] = val
pref = Container()
pref.personaldata.firstname = 'John'
pref.personaldata.lastname = 'Cleese'
pref.windowsettings.windowA.x = 200
print pref.personaldata.firstname
There's a few disadvantages to this: typos, for example, would become
canonical parts of objects, so perhaps the explicit [if ugly]
pref.personaldata = Container()
is necessary.
Because I really want to say
pref.personaldata = None
and I don't want to elimintae the possibility of saying
pref.personaldata = 23
pref.personaldata.detailed = 234
Danyel
"Stefan Schwarzer" <s.schwarzer at ndh.net> wrote in message
news:3C6C1761.6BB16ADA at ndh.net...
> Hello Michael
>
> Michael Chermside wrote:
> > Instead of using an empty function, use something designed specifically
> > for holding fields: a class!
> >
> > >>> class Empty:
> > pass
> > >>> pref = Empty()
> > >>> pref.personalData = Empty()
> > >>> pref.personalData.firstName = 'John'
> > >>> pref.personalData.lastName = 'Cleese'
> > >>> pref.windowSettings = Empty()
> > >>> pref.windowSettings.windowA = Empty()
> > >>> pref.windowSettings.windowA.x = 200
>
> Actually, you use instances of the class to store the values. I think,
> you meant that anyway, didn't you? :-)
>
> Sometimes classes are used for such a purpose. However, this may cause
> problems if you need more than one "container" (like above). Using
> class instances is more common, I assume.
>
> Stefan
More information about the Python-list
mailing list