dynamism

Raymond Hettinger python at rcn.com
Mon Sep 9 23:45:35 EDT 2002


"Steven Shaw" <steven_shaw at adc.com> wrote in message
> I thought that you could access dictionary values with object syntax:
>
> >>> x = { 'a': 1, 'b':2 }
> >>> x
> {'a': 1, 'b': 2}
> >>> x.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'dict' object has no attribute 'a'
>
> Maybe you could never do this as shown but I'm sure there were ways of
getting
> this effect. Anyone care to remind me?

>>> class AttrDict: pass

>>> ad = AttrDict()
>>> ad.__dict__ = {'a': 1, 'b':2}
>>> ad.a
1
>>> ad.b
2

>>> class BetterAttrDict(dict):
 def __getattr__(self, key):
  return dict.__getitem__(self, key)


>>> bad = BetterAttrDict({'a': 1, 'b':2})
>>> bad.a
1
>>> bad.b
2


Raymond Hettinger





More information about the Python-list mailing list