Note about getattr and '.'
Carl Banks
pavlovevidence at gmail.com
Tue Nov 21 16:46:08 EST 2006
szport at gmail.com wrote:
> There is an interesting skewness in python:
>
> class A(object): pass
>
> >>> a=A()
> >>> setattr(a, '$foo', 17)
> >>> getattr(a, '$foo')
> 17
>
> But I can't write
> >>> a.'$foo'
Likewise, you can write
setattr(a,'hello',17)
but you can't write
a.'hello'
but you can write
a.hello
The only thing that can follow the "." (attribute access) operator is a
valid Python identifier. Strings may not. Anyways, it's probably not
a good idea in most cases to use getattr and setattr with a
non-identifier, but Python doesn't prevent you from doing it. (Which
is good in the occasional case where it is a good idea.)
BTW, Matlab has an interesting syntax; you could have written this:
a.("$foo")
(And because Matlab is weird that way, this was not structure member
access, but some weird hybrid of structure accces and indexing and/or
slicing. The syntax was very useful in Matlab because there's no
built-in associative array and using this syntax was the easiest way to
get something like it. In Python we'd do that with a dict, so it's not
so useful here.)
Carl Banks
More information about the Python-list
mailing list