getattr nested attributes

Peter Otten __peter__ at web.de
Fri Aug 15 10:49:18 CEST 2008


Gregor Horvath wrote:

> Hi,
> 
> class A(object):
>      test = "test"
> 
> class B(object):
>      a = A()
> 
> 
> In [36]: B.a.test
> Out[36]: 'test'
> 
> In [37]: getattr(B, "a.test")
> ---------------------------------------------------------------------------
> <type 'exceptions.AttributeError'>        Traceback (most recent call
> last)
> 
> /<ipython console> in <module>()
> 
> <type 'exceptions.AttributeError'>: type object 'B' has no attribute
> 'a.test'
> 
> ???

I think that message is pretty clear. B doesn't have an attribute "a.test",
it has an attribute "a" which in turn has an attribute "test". You can
access it by calling getattr() twice,

>>> getattr(getattr(B, "a"), "test")
'test'

make your own function that loops over the attributes, or spell it

>>> reduce(getattr, "a.test".split("."), B)
'test'

> Documentation says B.a.test and getattr(B, "a.test") should be equivalent.
> 
> http://docs.python.org/lib/built-in-funcs.html

No, it doesn't.

Peter



More information about the Python-list mailing list