extend getattr()

George Sakkis george.sakkis at gmail.com
Thu Jun 26 18:43:45 CEST 2008


On Jun 26, 7:39 am, Cédric Lucantis <o... at no-log.org> wrote:

> Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez écrit :
>
> > Hello,
>
> > lets assume i have some classes:
>
> > class A(object):
> >     def __init__(self):
> >         b = B()
>
> > class B(object):
> >     def __init__(self):
> >         c = C()
>
> note you're just defining some local variables here, should be self.b = B()
> and self.c = C().
>
> > class C(object):
> >     def __init__(self):
> >         pass
>
> > and now i wanna do something like this:
>
> > 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?
>
> You could do it manually:
>
> c = getattr(getattr(a, 'b'), 'c')
>
> or make it automatic:
>
> def get_dotted_attr (obj, dotted_attr) :
>         for attr in dotted_attr.split('.') :
>                 obj = getattr(obj, attr)
>         return obj
>
> a = A()
> print 'a.b.c = %s' % get_dotted_attr(a, 'b.c')

FYI, this feature will exist in operator.attrgetter from Python 2.6,
i.e. you'll be able to say attrgetter('b.c')(a).

George



More information about the Python-list mailing list