extend getattr()

Gerhard Häring gh at ghaering.de
Thu Jun 26 07:31:40 EDT 2008


Rotlaus wrote:
> Hello,
> 
> lets assume i have some classes:
> [...]
> 
> a=A()
> c=getattr(a, 'b.c')
> 
> I know this doesn't work, but what can i do to get this or a similar
> functionality to get it work for this sample and for even more nested
> classes?

Just recursively apply the getattr(), like this:

class A(object):
     def __init__(self):
         self.b = B()

class B(object):
     def __init__(self):
         self.c = C()

class C(object):
     def __init__(self):
         pass

def ext_getattr(obj, attr):
     for subattr in attr.split("."):
         obj = getattr(obj, subattr)
     return obj

a=A()
c = ext_getattr(a, 'b.c')

-- Gerhard




More information about the Python-list mailing list