The meaning of "=" (Was: tough-to-explain Python)

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Mon Jul 13 13:22:36 CEST 2009


In message <h3bogf$oo0$1 at panix3.panix.com>, Aahz wrote:

> In article <h3bagu$52m$4 at lust.ihug.co.nz>,
> Lawrence D'Oliveiro  <ldo at geek-central.gen.new_zealand> wrote:
>>In message <h37gv5$r81$1 at panix3.panix.com>, Aahz wrote:
>>>
>>> It helps to remember that names and namespaces are in many
>>> ways syntactic sugar for dicts or lists.
>>
>>Interesting, though, that Python insists on maintaining a distinction
>>between c["x"] and c.x, whereas JavaScript doesn't bother.
> 
> Why do you say "insists"?
> 
> class AttrDict:
>     def __getitem__(self, key):
>         return getattr(self, key)

OK, let's try it:

    >>> c = {}
    >>> c["x"] = 3
    >>> c.x = 4   
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object has no attribute 'x'
    >>> class AttrDict:
    ...     def __getitem__(self, key):
    ...         return getattr(self, key)
    ...
    >>> c.x = 4
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object has no attribute 'x'

Nope, still doesn't work...




More information about the Python-list mailing list