The meaning of "="
Piet van Oostrum
piet at cs.uu.nl
Mon Jul 13 08:15:07 EDT 2009
>>>>> Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> (LD) wrote:
>LD> In message <h3bogf$oo0$1 at 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()
And to get c.x = 4 working you also need a __setitem__.
And to get c["x"] working AtrrDict should subclass dict:
>>> class AttrDict(dict):
but these are only minor details :=)
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org
More information about the Python-list
mailing list