In article <m24otg3hkk....@cs.uu.nl>, Piet van Oostrum <p...@cs.uu.nl> wrote: >>>>>> Lawrence D'Oliveiro <l...@geek-central.gen.new_zealand> (LD) wrote: > >>LD> In message <h3bogf$oo...@panix3.panix.com>, Aahz wrote: > >>Aahz> class AttrDict: >>Aahz> def __getitem__(self, key): >>Aahz> return getattr(self, key) > >>LD> OK, let's try it: > >>LD> >>> c = {} >>LD> >>> c["x"] = 3 >>LD> >>> c.x = 4 >>LD> Traceback (most recent call last): >>LD> File "<stdin>", line 1, in <module> >>LD> AttributeError: 'dict' object has no attribute 'x' >>LD> >>> class AttrDict: >>LD> ... def __getitem__(self, key): >>LD> ... return getattr(self, key) >>LD> ... >>LD> >>> c.x = 4 >>LD> Traceback (most recent call last): >>LD> File "<stdin>", line 1, in <module> >>LD> AttributeError: 'dict' object has no attribute 'x' > >>LD> Nope, still doesn't work... > >Of course you need c = AttrDict()
Absolutely -- Lawrence really needs to learn to do his own debugging. >And to get c.x = 4 working you also need a __setitem__. Nope. You do need __setitem__ so that this works: c['x'] = 4 >And to get c["x"] working AtrrDict should subclass dict: Definitely not. There's a perfectly good dict inside a regular class instance already. The only reason to subclass from dict is so that you get all the dict methods for free; however, the cost is that you get ugly bugs because of e.g. c['update'] = 'foo' Overally, I think it's much better/safer to explicitly pull the dict methods you want to use. -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." --Red Adair -- http://mail.python.org/mailman/listinfo/python-list