The meaning of "="
Piet van Oostrum
piet at cs.uu.nl
Wed Jul 15 04:14:20 EDT 2009
>>>>> aahz at pythoncraft.com (Aahz) (A) wrote:
>A> In article <m27hybyo95.fsf at cs.uu.nl>, Piet van Oostrum <piet at cs.uu.nl> wrote:
>>>>>>>> aahz at pythoncraft.com (Aahz) (A) wrote:
>>>
>A> In article <m24otg3hkk.fsf at cs.uu.nl>, Piet van Oostrum
>A> <piet at cs.uu.nl> wrote:
>>>
>>>>>> And to get c.x = 4 working you also need a __setitem__.
>>>
>A> Nope. You do need __setitem__ so that this works:
>>>
>A> c['x'] = 4
>>>
>>> Sorry, I meant such that c.x = 4 does the same as c['x'] = 4 because
>>> that was what the OP wanted (I think).
>A> c.x = 4
>A> already updates the instance dict, so there's no need to change any class
>A> methods to support it. That is, IME it's much better to add methods to
>A> a regular class to make it more dict-like using the built-in instance
>A> dict rather than changing any of the attribute mechanisms. If you're
>A> really curious, I recommend trying several approaches yourself to see
>A> what works better. ;-)
Yes, that's why I mentioned __setitem__. I just mixed up the motivation.
In [28]: class AttrDict:
....: def __getitem__(self, key):
....: return getattr(self, key)
....:
....: def __setitem__(self, key, value):
....: setattr(self, key, value)
....:
....:
In [29]: c = AttrDict()
In [30]: c["y"] = 3
In [31]: c.y
Out[31]: 3
In [32]: c.x = 4
In [33]: c['x']
Out[33]: 4
--
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