A.x vs. A["x"]

Steve Howell showell30 at yahoo.com
Fri Jan 22 20:59:29 CET 2010


On Jan 22, 11:29 am, Martin Drautzburg <Martin.Drautzb... at web.de>
wrote:
> This has probably been asekd a million times, but if someone could give
> a short answer anyways I's be most grateful.

Not sure there is exactly a short answer, and I am only qualified to
maybe clarify some of the things you can and cannot do, not explain
the reasons they are so.

> What is it that allows one to write A.x? If I have a variable A, then
> what to I have to assign to it to A.x becomes valid?


Although not super concise, you'll find some good reading here:

http://docs.python.org/tutorial/classes.html#a-word-about-names-and-objects

It maybe does not address your question exactly, but it might give you
insight into the overall philosophy.


> Or even further: what do I have to do so I can write A.x=1 without
> having done anything magical for x (but just for A)? I know you can do
> this with classes, but not with plain objects, but why is that so?


Here are examples where adding attributes on the fly does not work:

    Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
    [GCC 4.3.3] on linux2
    Type "help", "copyright", "credits" or "license" for more
information.
    >>> s = ''
    >>> s.x = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'str' object has no attribute 'x'

    >>> d = {}
    >>> d.x = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object has no attribute 'x'

    >>> n = 0
    >>> n.x = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'int' object has no attribute 'x'

Here are examples when you can assign new attributes:

    >>> class C: pass
    ...
    >>> C.x = 1
    >>> C().x = 1

    >>> def f(): pass
    ...
    >>> f.x = 1

    >>> lam = lambda n: n
    >>> lam.x = 1

Hope that helps or at least gets the discussion started.




More information about the Python-list mailing list